列表联合与重复

时间:2011-09-15 12:37:02

标签: python

我需要在Python3中统一两个列表,其中可以存在重复项,并且对于其中一组,结果列表将在两个列表中包含尽可能多的最大值。示例可能会澄清它:

[1,2,2,5]( some operator)[2,5,5,5,9]=[1,2,2,5,5,5,9]

想法?

3 个答案:

答案 0 :(得分:13)

您可以使用collections.Counter类:

>>> from collections import Counter
>>> combined = Counter([1,2,2,5]) | Counter([2,5,5,5,9])
>>> list(combined.elements())
[1, 2, 2, 5, 5, 5, 9]

它充当multiset(无序集合,其中每个元素可以多次出现)。 |运算符为您提供了多重集合的并集,其中每个元素都显示为max(apperances_in_counter1,appearances_in_counter2)次。

这个类是在Python 2.7和3.1中添加的。

答案 1 :(得分:2)

为什么首先使用列表?这些数据对我来说就像一个字典:

[1,2,2,5] -> {1: 1, 2: 2, 5: 1}
[2,5,5,5,9] -> {2: 1, 5: 3, 9: 1}

然后很简单:

keys = set(a.keys()+b.keys())
vals = [max(a.get(n, 0), b.get(n, 0)) for n in keys]
d = dict(zip(keys, vals))
print d

结果:

  

{1:1,2:2,5:3,9:1}

答案 2 :(得分:1)

  1. 使用a[key] = count

  2. 将数组转换为字典
  3. 使用规则c[key] = a.get(key, 0) > b.get(key, 0) and a[key] or b[key]创建新词典。你需要在a和b dicts中迭代两个键。

  4. 展开词典,result += [value] * key