简体   繁体   English

比较元组和列表之间的元素?

[英]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)] .假设我有一个元组k1= ((91, 25),(94, 27),(100, 22))和一个列表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?如何比较k1k2的元素并获得公共元素的列表?

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. ^运算符 + list comprehension用于获取相反的值。

Or Even better:或者更好:

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

I recommend this, it's the shortest我推荐这个,这是最短的

You can use filter Function您可以使用filter功能

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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