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)

您不需要inventory函数:Counter将为您计算可迭代数。您也可以将+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提供的实现是最优的。

这里有另一种不用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}

最新更新