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

2024-06-15 13:48:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字典,在多个键下有多个值。我不想要一个值的总和。我想找到一种方法来计算每个键的和。 该文件用制表符分隔,标识符是这两个项的组合,即Btarg。每个标识符都有多个值。
下面是一个测试文件: 下面是测试结果:

图案项目丰度

1蚂蚁2

2只狗10只

3长颈鹿15

1蚂蚁4

2只狗5

以下是预期结果:

图案1,6

图案2dog,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)

在Python3中,如果没有错误消息“Unsupported operand type for+:'int'and'list'? 提前谢谢!在


Tags: 文件keyinforifline标识符find
1条回答
网友
1楼 · 发布于 2024-06-15 13:48:39

使用from collections import Counter

documentation

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

对于你的评论,现在我想我知道你想要什么,尽管我不知道你的数据是什么结构。我认为您可以像这样组织数据:

^{pr2}$

首先创建一个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})

相关问题 更多 >