list是另一个列表的子集

时间:2011-06-24 22:20:13

标签: python list subset

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

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

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

2 个答案:

答案 0 :(得分:11)

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

答案 1 :(得分:8)

为了提供替代方案,也许使用元组和集更有效:

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