>> b = ["a","b","c","d","e","f"] >>> #Do so-6ren">
gpt4 book ai didi

python - 从一个列表中删除另一个列表的元素,同时保留重复项

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:29:22 25 4
gpt4 key购买 nike

基本上我想要的是:

>>> a = ["a","a","b","c","c","c","d","e","f"]
>>> b = ["a","b","c","d","e","f"]
>>> #Do something, something like a - b
>>> result = ["a","c","c"]

我想这样做的原因是,我加入了一堆偏好列表,并想在众多列表中找出哪一个是常见的。它们在列表 a 中出现的次数越多(因为更多的列表包含该元素),我对此的重视程度就越高

最佳答案

您确实在寻找多重集。使用 collections.Counter() ,多重集的 Python 实现:

from collections import Counter

acount = Counter(a)
bcount = Counter(b)
result = list((acount - bcount).elements())

演示:

>>> from collections import Counter
>>> a = ['a', 'a', 'b', 'c', 'c', 'c', 'd', 'e', 'f']
>>> b = ['a', 'b', 'c', 'd', 'e', 'f']
>>> Counter(a) - Counter(b)
Counter({'c': 2, 'a': 1})
>>> list((Counter(a) - Counter(b)).elements())
['a', 'c', 'c']

不过,您可能希望保留 Counter() 实例;但如果您需要它,Counter.elements() 方法会生成一系列元素乘以它们的计数,以再次产生您想要的输出。

关于python - 从一个列表中删除另一个列表的元素,同时保留重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18580032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com