在Python中,给出了两个配对列表:

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

如果listB是listA的子集,如何有效地编写返回True的python函数?哦,[1,20]对等效于[20,1]

最佳答案

使用 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

关于python - 列表是另一个列表的子集,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6474352/

10-11 20:31