python - Check if two unordered lists are equal -
this question has answer here:
i'm looking easy (and quick) way determine if 2 unordered lists contain same elements:
for example:
['one', 'two', 'three'] == ['one', 'two', 'three'] : true ['one', 'two', 'three'] == ['one', 'three', 'two'] : true ['one', 'two', 'three'] == ['one', 'two', 'three', 'three'] : false ['one', 'two', 'three'] == ['one', 'two', 'three', 'four'] : false ['one', 'two', 'three'] == ['one', 'two', 'four'] : false ['one', 'two', 'three'] == ['one'] : false
i'm hoping without using map.
python has built-in datatype unordered collection of (hashable) things, called set
. if convert both lists sets, comparison unordered.
set(x) == set(y)
edit: @mdwhatcott points out want check duplicates. set
ignores these, need similar data structure keeps track of number of items in each list. called multiset; best approximation in standard library collections.counter
:
>>> import collections >>> compare = lambda x, y: collections.counter(x) == collections.counter(y) >>> >>> compare([1,2,3], [1,2,3,3]) false >>> compare([1,2,3], [1,2,3]) true >>> compare([1,2,3,3], [1,2,2,3]) false >>>
Comments
Post a Comment