开发者

multi-parameter 'in' in python

Let L = [1,2,3,4] be our list.

Then 1 in L is True. 2 in L is also True.

Is there a clean way to write (1,2) in L and have it come out true?

That is, given a list L and a test list T and the relation multi-in, if all members of T are in L, then T multi-in L is True, otherwi开发者_运维问答se T multi-in L is False.

Of course I can write a multi-in function, but that seems ugly.


You want to treat (1,2) and L as sets:

set((1,2)).issubset(L)

or, nicer if you understand the notation:

set((1,2)) <= set(L)


all(x in L for x in [1, 2])

Unlike the set-based solutions, this (1) short-curcuits as soon as an element isn't found, (2) works for unhashable types and (3) reads out nice ;)

We can go improve complexity (O(n*m) currently) by going back to sets... although in a different way: Convert L to a set beforehand and you get O(1) membership test back (without needing a second set for the items to check for).


How about:

set((1,2)).issubset(L)


Use sets:

  s = set([1,2])
  l = set([1,2,3,4])

  s.issubset(l)

The .issubset() method will tell you if all the elements in one set exist in another.


Good answers above. Another possibility is:

all(x in L for x in [1,2,3,4])

I'm not dutch, but that's the "single obvious way to do it" to me.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜