繁体   English   中英

如何在Python 3中计算字典中的每组值?

[英]How to count each group of values in a dictionary in Python 3?

我有一本字典,在多个键下有多个值。 我不希望值的总和。 我想找到一种方法来找到每个键的总和。 该文件用制表符分隔,标识符是Btarg这两项的组合。 这些标识符中的每一个都有多个值。
这是一个测试文件:这是一个具有所需结果的测试文件:

模式项的丰度

1蚂蚁2

2狗10

3长颈鹿15

1蚂蚁4

2狗5

这是预期的结果:

Pattern1Ant,6

Pattern2Dog,15岁

图案3长颈鹿,15

这是我到目前为止的内容:

for line in K:

    if "pattern" in line:
        find = line
        Bsplit = find.split("\t")
        Buid = Bsplit[0]
        Borg = Bsplit[1]
        Bnum = (Bsplit[2])
        Btarg = Buid[:-1] + "//" + Borg


        if Btarg not in dict1:
            dict1[Btarg] = []
        dict1[Btarg].append(Bnum)
    #The following used to work
    #for key in dict1.iterkeys():
        #dict1[key] = sum(dict1[key])
    #print (dict1)

如何在Python 3中实现此功能,而不会出现错误消息“ +:'int'和'list'不支持的操作数类型?”在此先感谢您!

from collections import Counter

文档中

c = Counter('gallahad')
Counter({'a': 3, 'l': 2, 'h': 1, 'g': 1, 'd': 1})

回应您的评论,现在我想我知道您想要什么,尽管我不知道您的数据采用的结构。我认为您可以像这样组织数据是理所当然的:

In [41]: d
Out[41]: [{'Ant': 2}, {'Dog': 10}, {'Giraffe': 15}, {'Ant': 4}, {'Dog': 5}]

首先创建一个defaultdict

from collections import defaultdict
a = defaultdict(int)

然后开始计算:

In [42]: for each in d:
            a[each.keys()[0]] += each.values()[0]

结果:

In [43]: a
Out[43]: defaultdict(<type 'int'>, {'Ant': 6, 'Giraffe': 15, 'Dog': 15})

更新2

假设您可以使用以下格式获取数据:

In [20]: d
Out[20]: [{'Ant': [2, 4]}, {'Dog': [10, 5]}, {'Giraffe': [15]}]

In [21]: from collections import defaultdict

In [22]: a = defaultdict(int)

In [23]: for each in d:
    a[each.keys()[0]] =sum(each.values()[0])
   ....:     

In [24]: a
Out[24]: defaultdict(<type 'int'>, {'Ant': 6, 'Giraffe': 15, 'Dog': 15})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM