我正在寻找一个简单(快速)的方法来确定两个无序列表是否包含相同的元素:
例如:
['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
我希望不用地图就能做到。
对上述问题的一个简单回答是:-
设两个列表为list1和list2,
你的要求是确保两个列表是否有相同的元素,那么在我看来,以下将是最好的方法:-
if ((len(list1) == len(list2)) and
(all(i in list2 for i in list1))):
print 'True'
else:
print 'False'
上面这段代码将根据您的需要工作,即是否list1的所有元素都在list2中,反之亦然。
但如果你只是想检查list1的所有元素是否都出现在list2中,那么你只需要使用下面的代码段:-
if all(i in list2 for i in list1):
print 'True'
else:
print 'False'
区别在于,如果list2包含一些额外的元素以及list1的所有元素,后者将打印True。简单地说,它将确保list1的所有元素都应该出现在list2中,而不管list2是否有一些额外的元素。
您希望查看它们是否包含相同的元素,但不关心顺序。
你可以使用一个集合:
>>> set(['one', 'two', 'three']) == set(['two', 'one', 'three'])
True
但是set对象本身只包含每个唯一值的一个实例,并且不会保持顺序。
>>> set(['one', 'one', 'one']) == set(['one'])
True
所以,如果跟踪副本/长度很重要,你可能还想检查长度:
def are_eq(a, b):
return set(a) == set(b) and len(a) == len(b)