开发者

Cross Reference 2 lists in Python 2.x

I am new to Python (using 2.6 and 2.7), but I have searched docs.Python.org and this site. I have found a similar question: Comparing lists in Python

...But I want to cross-reference 2 lists of different sizes and unknown orders. Here is an example开发者_开发技巧 of what I want to do:

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

# magic happens here

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

Giving a result of common entries. Knowing Python it seems there would probably be a simple/elegant solution to such a simple problem.


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

If you need the result to be a list, if you're okay leaving it as a set then just

set(mammals) & set(apes)


Use sets:

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

prints

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


This is perfect for the set built-in type.

Make the base list a set:

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

Then use the intersection function (the compared list doesn't have to be a set)

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜