Comparing elements between a tuple and list?

Viewed 632

I am comparing between a tuple of tuples and a list of tuples. I need to get the common elements out in a list.

Suppose that I have a tuple k1= ((91, 25),(94, 27),(100, 22)) and a list k2 = [(1,2), (4, 2), (100, 22)]. How do I compare the elements in k1 and k2 and get a list of the common elements?

Expected output for the above example:

[(100, 22)]
5 Answers

You can use set intersection:

set(k1).intersection(k2)

This returns:

{(100, 22)}

You can use a simple list comprehension for that,

common_items = [item1 for item1 in list(k1) for item2 in k2 if item1 == item2]

Here's the output,

>>> common_items

[(100, 22)]
[i for i in k1 if i in k2]

you can use a simple list comprehension to iterate through each tuple in the lists and compare from there

Or:

print([i for i in b if i not in (set(a)^set(b))])

^ operator + list comprehension for getting the opposite values.

Or Even better:

print(set(a)&set(b))

I recommend this, it's the shortest

You can use filter Function

k1 = ((91, 25),(94, 27),(100, 22))
k2 = [(1,2), (4, 2), (100, 22)]
print filter(lambda x: x in k1,k2)

Result:

[(100, 22)]
Related