开发者

list is a subset of another list

in Python, given two lists of pairs:

listA = [ [1,20], [3,19], [37,11], [21,17] ]
listB = [ [1,20], [21,17] ]

how do you efficiently write a python function which return True if listB is a subset of listA? oh and [1,20] pair is equivalent to [开发者_如何学JAVA20,1]


Use frozenset.

>>> listA = [ [1,20], [3,19], [37,11], [21,17] ]
>>> listB = [ [1,20], [21,17] ]

>>> setA = frozenset([frozenset(element) for element in listA])
>>> setB = frozenset([frozenset(element) for element in listB])

>>> setA
frozenset([frozenset([17, 21]), frozenset([1, 20]), frozenset([11, 37]), frozens
et([19, 3])])
>>> setB
frozenset([frozenset([17, 21]), frozenset([1, 20])])

>>> setB <= setA
True


Just in order to offer an alternative, perhaps using tuple and set is more efficient:

>>> set(map(tuple,listB)) <= set(map(tuple,listA))
True
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜