【问题标题】:How to compare lists without using set() ? Python3 [duplicate]如何在不使用 set() 的情况下比较列表? Python3 [重复]
【发布时间】:2017-03-04 01:18:48
【问题描述】:

我想从 2 个列表中获取常用元素。 我不能将 set() 用于具有可重复对象的列表,因为会发生这种情况:

list1=set([5, 5, 5])
list2=set([5, 5])
list3=list1.intersection(list2)
print(list3) ---> {5}

感谢您的帮助!

【问题讨论】:

  • 使用collections.Counter

标签: python-3.x


【解决方案1】:

使用collections.Counter

from collections import Counter
list1 = [5,5,5,4]
list2 = [5,5,4,4]

result = Counter(list1) & Counter(list2) # & is intersection


>>> result
Counter({5: 2, 4: 1})
>>> list(result.elements())
[4, 5, 5]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-24
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    • 2021-07-12
    相关资源
    最近更新 更多