开发者

intersect two lists of words in python

i want to find the intersection of two lists in python. i have something that looks like this:

>>> q = ['apple', 'peach', 'pear', 'watermelon', 'strawberry']
>>> w = ['pineapple', 'peach', 'watermelon', 'kiwi']

and i want to find something that looks like this:

t = ['peach', 'watermelon']

i know its a simple, que开发者_JS百科stion but im new to python--does anyone have any suggestions?


The intersection() method is available for sets, which can be easily made from lists.

ETA: if you want a list out of it...

q = ['apple', 'peach', 'pear', 'watermelon', 'strawberry']
w = ['pineapple', 'peach', 'watermelon', 'kiwi']
t = list(set(q) & set(w))

Now t is:

['watermelon', 'peach']


The preferred way of doing it is via set intersection:

list(set(q) & set(w))

If the lists are short, a list comprehension should work.

t = [x for x in q if x in w]

However, beware, this is O(n^2), so it is not very efficient with long lists.


It was discussed here on SO that intersection works a bit faster, so you can use:

q = ['apple', 'peach', 'pear', 'watermelon', 'strawberry']
w = ['pineapple', 'peach', 'watermelon', 'kiwi']
set(q).intersection(w)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜