Python计数器无法识别字典

2024-05-12 23:20:49 发布

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

我有一个列表和一个字典,我想最终找到这两个值的总和。例如,我希望下面的代码返回:

{gold coin : 45, rope : 1, dagger : 6, ruby : 1}

首先我右击一个函数,将dragonLoot列表转换为一个字典,然后运行一个计数器将这两个字典添加到一起。但是,当我运行代码时,会得到以下结果:

{'ruby': 1, 'gold coin': 3, 'dagger': 1}
Counter({'gold coin': 42, 'dagger': 5, 'rope': 1})

出于某种原因,计数器似乎无法识别我从dragonLoot创建的字典。有人对我做错了什么有什么建议吗?谢谢!你知道吗

inv = {'gold coin' : 42, 'rope' : 1, 'dagger' : 5}
dragonLoot = ['gold coin','dagger','gold coin','gold coin','ruby']

def inventory(item):
    count = {}
    for x in range(len(item)):
        count.setdefault(item[x],0)
        count[item[x]] = count[item[x]] + 1
    print(count)

inv2 = inventory(dragonLoot)

from collections import Counter
dicts = [inv,inv2]
c = Counter()
for d in dicts:
    c.update(d)

print(c)

Tags: 代码列表字典countcounter计数器iteminventory
3条回答

下面是另一种不用Counter的方法:

dragonLoot = ['gold coin','dagger','gold coin','gold coin','ruby']
inv = {'gold coin' : 42, 'rope' : 1, 'dagger' : 5}
for i in dragonLoot:
    inv[i] = inv.get(i, 0) +1
print (inv)

输出:

{'gold coin': 45, 'rope': 1, 'dagger': 6, 'ruby': 1}

您不需要inventory函数:Counter将为您计算iterable。也可以将+Counter一起使用。把这些结合起来,你就可以做得很简单

inv = Counter({'gold coin' : 42, 'rope' : 1, 'dagger' : 5})
dragonLoot = ['gold coin','dagger','gold coin','gold coin','ruby']

inv += Counter(dragonLoot)

运行此命令后,inv将根据需要Counter({'gold coin': 45, 'dagger': 6, 'rope': 1, 'ruby': 1})。你知道吗

您没有在库存方法中返回计数:

def inventory(item):
    count = {}
    for x in range(len(item)):
        count.setdefault(item[x],0)
        count[item[x]] = count[item[x]] + 1
    print(count)

您只需打印您的库存计算。将打印更改为退货,或在打印后添加退货行:

def inventory(item):
    count = {}
    for x in range(len(item)):
        count.setdefault(item[x],0)
        count[item[x]] = count[item[x]] + 1
    print(count)
    return count

将其添加到代码中并运行,将得到以下输出:

Counter({'gold coin': 45, 'dagger': 6, 'rope': 1, 'ruby': 1})

或者,@nneonneo提供的实现是最佳的。你知道吗

相关问题 更多 >