通过两个元素的集合合并两个数组

cha*_*e55 2 python arrays

我有一个包含偶数个整数的数组.该数组表示标识符和计数的配对.元组已经按标识符排序.我想将这些数组中的一些合并在一起.我想到了几种方法,但它们相当复杂,我觉得用python可能有一种简单的方法.

IE:

[<id>, <count>, <id>, <count>]
Run Code Online (Sandbox Code Playgroud)

输入:

[14, 1, 16, 4, 153, 21]
[14, 2, 16, 3, 18, 9]
Run Code Online (Sandbox Code Playgroud)

输出:

[14, 3, 16, 7, 18, 9, 153, 21]
Run Code Online (Sandbox Code Playgroud)

Dav*_*son 8

最好将它们存储为字典而不是列表(不仅仅是为了这个目的,而是针对其他用例,例如提取单个ID的值):

x1 = [14, 1, 16, 4, 153, 21]
x2 = [14, 2, 16, 3, 18, 9]

# turn into dictionaries (could write a function to convert)
d1 = dict([(x1[i], x1[i + 1]) for i in range(0, len(x1), 2)])
d2 = dict([(x2[i], x2[i + 1]) for i in range(0, len(x2), 2)])

print d1
# {16: 4, 153: 21, 14: 1}
Run Code Online (Sandbox Code Playgroud)

之后,您可以使用此问题中的任何解决方案将它们添加到一起.例如(取自第一个答案):

import collections

def d_sum(a, b):
    d = collections.defaultdict(int, a)
    for k, v in b.items():
        d[k] += v
    return dict(d)

print d_sum(d1, d2)
# {16: 7, 153: 21, 18: 9, 14: 3}
Run Code Online (Sandbox Code Playgroud)


Mar*_*ers 5

用途collections.Counter:

import itertools
import collections

def grouper(n, iterable, fillvalue=None):
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)

count1 = collections.Counter(dict(grouper(2, lst1)))
count2 = collections.Counter(dict(grouper(2, lst2)))
result = count1 + count2
Run Code Online (Sandbox Code Playgroud)

我在这里使用了itertoolsgrouper配方将你的数据转换为字典,但正如其他答案已经向你展示的那样,你可以通过更多的方式来修饰特定的猫.

resultCounter每个id指向总计数:

Counter({153: 21, 18: 9, 16: 7, 14: 3})
Run Code Online (Sandbox Code Playgroud)

Counters是多套的,可以轻松跟踪每个密钥的数量.对您的数据来说,这感觉就像是一个更好的数据结构.例如,它们支持求和,如上所述.


Ash*_*ary 5

collections.Counter() 这就是你需要的:

In [21]: lis1=[14, 1, 16, 4, 153, 21]

In [22]: lis2=[14, 2, 16, 3, 18, 9]

In [23]: from collections import Counter

In [24]: dic1=Counter(dict(zip(lis1[0::2],lis1[1::2])))

In [25]: dic2=Counter(dict(zip(lis2[0::2],lis2[1::2])))

In [26]: dic1+dic2
Out[26]: Counter({153: 21, 18: 9, 16: 7, 14: 3})
Run Code Online (Sandbox Code Playgroud)

要么 :

In [51]: it1=iter(lis1)

In [52]: it2=iter(lis2)

In [53]: dic1=Counter(dict((next(it1),next(it1)) for _ in xrange(len(lis1)/2))) 
In [54]: dic2=Counter(dict((next(it2),next(it2)) for _ in xrange(len(lis2)/2))) 
In [55]: dic1+dic2
Out[55]: Counter({153: 21, 18: 9, 16: 7, 14: 3})
Run Code Online (Sandbox Code Playgroud)