开发者

Pythonic way of saying "if all of the elements in list 1 also exist in list 2"

I want to return true from the if statem开发者_如何学编程ent only if all of the elements from list 1 also exist in list 2 (list 2 is a superset of list 1). What is the most pythonic way of writing this?


You can use set operations:

if set(list1) <= set(list2):
    #...

Note that the comparison itself is fast, but converting the lists to sets might not (depends on the size of the lists).

Converting to a set also removes any duplicate. So if you have duplicate elements and want to ensure that they are also duplicates in the other list, using sets will not work.


You can use built-in all() function:

if all(x in sLVals for x in fLVals):
    # do something

In case of using sets think you can take a look at difference method as far as i know it is quite faster way:

if set(fLVals).difference(sLVals):
    # there is a difference
else:
    # no difference


Either set.issuperset or all(x in L2 for x in L1).


This one came straight out of good folks at MIT:

from operator import and_
reduce(and_, [x in b for x in a])

I tried to find the "readings.pdf" they had posted for the 6.01 class about a year ago...but I can't find it anymore.

Head to my profile and send me an email, and I'll send you the .pdf where I got this example. It's a very good book, but it doesn't seem to be a part of the class anymore.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜