Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有两个列表如下:
a = ['abc','def', 'ghi'], b=['ZYX','WVU']
并想确认union两个列表是否等于超集
union
c = ['ZYX', 'def', 'WVU', 'ghi', 'abc']
我试过以下:
>>> print (c == list(set(b).union(c))) >>> False
任何人都可以展示我在这里缺少的东西吗?
只需使用set方法,因为列表中的项目顺序不同,这就是您收到False结果的原因。
set
False
print (set(c) == set(list(set(b).union(c))))
另一种解决方案是使用Counter类。该Counter方法对于大列表应该更有效,因为它具有线性时间复杂度(即 O(n))
Counter
from collections import Counter Counter(c) == Counter(list(set(b).union(c))))