简体   繁体   中英

Comparing elements between a tuple and list?

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)]

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]

您可以使用简单的列表理解来遍历列表中的每个元组并从那里进行比较

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM