For advice on how to find the A tuples that element exists in the B tuple

A = (1,2,3)
B = (2,3,4,5)

With what method can easily find out the A that exists in the B, or for those who don't exist in B
Thank you

Started by Lori at February 12, 2016 - 6:39 AM

  1. >>> A = (1,2,3)
  2. >>> B = (2,3,4,5)
  3. >>> [i for i in A if i in B]
  4. [2, 3]
  5. >>> [i for i in A if i not in B]
  6. [1]

Posted by Alger at February 18, 2016 - 6:40 AM

  1. set(A).intersection(B)
one way to do it

Posted by Ulysses at February 26, 2016 - 6:49 AM

Thank you
#Method:
a=[2,3,4,5]
b=[2,5,8]
tmp = [val for val in a if val in b]
print tmp
#[2, 5]

#Methods two
print list(set(a).intersection(set(b)))

Union of 2 to get two list
print list(set(a).union(set(b)))

3 to get two list difference sets
print list(set(b).difference(set(a))) # B are not found in the a.

Posted by Lori at February 28, 2016 - 7:01 AM

All methods of set second parameter need not be set, Iterable as long as you can

Posted by Ulysses at March 06, 2016 - 7:27 AM

Thank you for your reply

Posted by Lori at March 10, 2016 - 8:16 AM

A = (1,2,3)
B = (2,3,4,5)

With what method can easily find out the A that exists in the B, or for those who don't exist in B
A in B
set(A) & set(B)
A is not in B
set(A) - set(B)

Posted by Rudolf at March 20, 2016 - 8:22 AM

A=(1,2,3)
N=[]
B=[2,3,4,5]

for i in A:
for j in B:
if i==j:
N.append(i)
B.remove(i)
break

print N,'common in A and B'
print B, 'only exist in B'

Posted by Asa at March 23, 2016 - 8:56 AM