Python 2.x中的交叉引用2列表

时间:2011-02-21 22:05:22

标签: python list

我是Python的新手(使用2.6和2.7),但我搜索了docs.Python.org和这个网站。我发现了一个类似的问题: Comparing lists in Python

...但我想交叉引用2个不同大小和未知订单的列表。 这是我想要做的一个例子:

>>> mammals = ["gorilla","cat","rat","chimpanzee","dog","beaver"]
>>> apes =  ["orangutan","chimpanzee","human","gorilla"]

# magic happens here

>>> print result # order doesn't matter
['chimpanzee', 'gorilla']

给出常见条目的结果。知道Python似乎可能会有一个简单/优雅的解决方案来解决这个简单的问题。

3 个答案:

答案 0 :(得分:1)

使用套装:

mammals = ["gorilla","cat","rat","chimpanzee","dog","beaver"]
apes =  ["orangutan","chimpanzee","human","gorilla"]
print set(mammals).intersection(apes)

打印

set(['gorilla', 'chimpanzee'])

答案 1 :(得分:1)

list(set(mammals) & set(apes))

如果您需要将结果作为列表,如果您可以将其保留为一组,那么只需

set(mammals) & set(apes)

答案 2 :(得分:0)

这适用于set内置类型。

使基本列表成为一组:

mammals = set(["gorilla","cat","rat","chimpanzee","dog","beaver"])

然后使用交叉函数(比较列表不必是一组)

>>> mammals.intersection(["orangutan","chimpanzee","human","gorilla"])
set(['gorilla', 'chimpanzee'])