开发者

How can I test if a list contains another list with particular items in Python?

I have a list of lists and want to check if it already contains a list with particular items.

Everything should be clear from this example:

list = [[1,2]开发者_如何学Go,[3,4],[4,5],[6,7]]
for test in [[1,1],[1,2],[2,1]]:
  if test in list:
    print True
  else:
    print False

#Expected:
#        False
#        True
#        True

#Reality:
#        False
#        True
#        False

Is there a function that compares the items of the list regardless how they are sorted?


What you want to use is a set: set([1,2]) == set([2,1]) returns True.

So

list = [set([1,2]),set([3,4]),set([4,5]),set([6,7])]
set([2,1]) in list

also returns True.


If they're really sets, use the set type

# This returns True 
set([2,1]) <= set([1,2,3])

<= means 'is a subset of' when dealing with sets. For more see the operations on set types.


if you want to get [1,2] = [2,1] you should not use list. Set is the correct type. In list, the order of the components matter, in set they don't. That's why you don't get 'False True True'.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜