dimka
dimka

Reputation: 4579

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 [20,1]

Upvotes: 5

Views: 6405

Answers (2)

Santa
Santa

Reputation: 11547

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

Upvotes: 11

fransua
fransua

Reputation: 1608

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

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

Upvotes: 8

Related Questions