Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 通过两个元素的集合合并两个数组_Python_Arrays - Fatal编程技术网

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

Python 通过两个元素的集合合并两个数组,python,arrays,Python,Arrays,我有一个包含偶数个整数的数组。数组表示标识符和计数的配对。元组已按标识符排序。我想将这些数组中的一些合并在一起。我已经想到了几种方法,但是它们相当复杂,我觉得用python可能有一种简单的方法 即: 输出: [14, 3, 16, 7, 18, 9, 153, 21] 使用: 我用这里的方法将你的数据转换成字典,但正如其他答案所显示的,有更多的方法可以剥那只猫的皮 结果是一个计数器,每个id都指向一个总计数: Counter({153: 21, 18: 9, 16: 7, 14: 3}) 计

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

即:

输出:

[14, 3, 16, 7, 18, 9, 153, 21]
使用:

我用这里的方法将你的数据转换成字典,但正如其他答案所显示的,有更多的方法可以剥那只猫的皮

结果
是一个
计数器
,每个id都指向一个总计数:

Counter({153: 21, 18: 9, 16: 7, 14: 3})

计数器
s是多组计数器,可以轻松跟踪每个键的计数。对于您的数据来说,它是一种更好的数据结构。例如,它们支持如上所述的求和。

将它们存储为字典比存储为列表更好(不仅出于此目的,而且对于其他用例,例如提取单个ID的值):

之后,您可以使用中的任何解决方案将它们添加到一起。例如(摘自):

您需要的是:

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})
或:


前面的所有答案看起来都不错,但我认为JSON blob应该首先正确形成,否则(根据我的经验),它可能会在调试过程中导致一些严重问题,等等。在本例中,id和count作为字段,JSON应该如下所示

[{"id":1, "count":10}, {"id":2, "count":10}, {"id":1, "count":5}, ...]
像这样格式正确的JSON更容易处理,而且可能与您即将介绍的内容类似

这个类有点通用,但肯定是可扩展的


1.
{'count':2,'junk':2,'id':1}
{'count':4,'junk':2,'id':1}
{'count':6,'junk':2,'id':1}
2.
{'count':2,'junk':2,'id':2}
{'count':3,'junk':2,'id':2}
{'count':3,'junk':2,'id':2}
3.
{'count':10,'junk':2,'id':3}

{1:12,2:8,3:10}


为什么这些不存储为字典?元组不是python元组,只是contiguos元素,对吗?我是python新手,如果有简单的方法将这些数据转换为字典,我完全支持。我从一个JSON数据包中获取数据。有相当数量的数据,所以我这样传输以节省空间。给定数组中的id是否保证唯一?或者它们可以在单个阵列中显示多次?这些数组一般有多大?ID是唯一的,我必须合并10-20个数组,每个5k到50k元素longI有50k元素。我避免使用那种风格的JSON,因为它会将消息的大小增加10倍。是的,这可能会对服务器造成负担。取决于它被击中的频率。但根据我的经验,格式良好的JSON让生活更美好。。。
Counter({153: 21, 18: 9, 16: 7, 14: 3})
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}
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}
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})
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})
[{"id":1, "count":10}, {"id":2, "count":10}, {"id":1, "count":5}, ...]

from itertools import groupby
class ListOfDicts():
    def init_(self, listofD=None):
        self.list = []
        if listofD is not None:
            self.list = listofD

    def key_total(self, group_by_key, aggregate_key):
        """ Aggregate a list of dicts by a specific key, and aggregation key"""
        out_dict = {}
        for k, g in groupby(self.list, key=lambda r: r[group_by_key]):
            print k
            total=0
            for record in g:
                print "   ", record
                total += record[aggregate_key]
            out_dict[k] = total
        return out_dict


if __name__ == "__main__":
    z = ListOfDicts([ {'id':1, 'count':2, 'junk':2}, 
                   {'id':1, 'count':4, 'junk':2},
                   {'id':1, 'count':6, 'junk':2},
                   {'id':2, 'count':2, 'junk':2}, 
                   {'id':2, 'count':3, 'junk':2},
                   {'id':2, 'count':3, 'junk':2},
                   {'id':3, 'count':10, 'junk':2},
                   ])

    totals = z.key_total("id", "count")
    print totals

1
    {'count': 2, 'junk': 2, 'id': 1}
    {'count': 4, 'junk': 2, 'id': 1}
    {'count': 6, 'junk': 2, 'id': 1}
2
    {'count': 2, 'junk': 2, 'id': 2}
    {'count': 3, 'junk': 2, 'id': 2}
    {'count': 3, 'junk': 2, 'id': 2}
3
    {'count': 10, 'junk': 2, 'id': 3}

{1: 12, 2: 8, 3: 10}