简体   繁体   English

比较python中两个列表中的元素

[英]Compare elements in two lists in python

I have two lists as below: 我有两个列表,如下所示:

a = ['abc','def', 'ghi'], b=['ZYX','WVU']

and want to confirm whether union of both lists is equal to superset 并要确认是否union两份名单等于超集

c = ['ZYX', 'def', 'WVU', 'ghi', 'abc'] 

I have tried following: 我尝试了以下方法:

>>> print (c == list(set(b).union(c)))
>>> False

Can anybody show what I am missing here? 有人可以显示我在这里想念的东西吗?

Just use set method because the items order in the lists are different and that's why you've received False as result. 只需使用set方法,因为列表中的项目顺序是不同的,这就是为什么您收到False作为结果的原因。

print (set(c) == set(list(set(b).union(c))))

Another solution is to use Counter class. 另一个解决方案是使用Counter类。 The Counter approach should be more efficient for big lists since it has linear time complexity (ie O(n)) 对于大型列表, Counter方法应该更有效,因为它具有线性时间复杂度(即O(n))

from collections import Counter
Counter(c) == Counter(list(set(b).union(c))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM