bsk*_*ets 1 python dictionary list python-3.x
假设我有dict = {'a':1,'b':2'}我还有一个列表= ['a','b,'c','d','e'].目标是将列表元素添加到字典中,并打印出新的dict值以及这些值的总和.应该是这样的:
2 a
3 b
1 c
1 d
1 e
Total number of items: 8
Run Code Online (Sandbox Code Playgroud)
相反,我得到:
1 a
2 b
1 c
1 d
1 e
Total number of items: 6
Run Code Online (Sandbox Code Playgroud)
到目前为止我所拥有的:
def addToInventory(inventory, addedItems)
for items in list():
dict.setdefault(item, [])
def displayInventory(inventory):
print('Inventory:')
item_count = 0
for k, v in inventory.items():
print(str(v) + ' ' + k)
item_count += int(v)
print('Total number of items: ' + str(item_count))
newInventory=addToInventory(dict, list)
displayInventory(dict)
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激!
您只需迭代列表并根据密钥递增计数(如果已存在),否则将其设置为1.
>>> d = {'a': 1, 'b': 2}
>>> l = ['a', 'b', 'c', 'd', 'e']
>>> for item in l:
... if item in d:
... d[item] += 1
... else:
... d[item] = 1
>>> d
{'a': 2, 'c': 1, 'b': 3, 'e': 1, 'd': 1}
Run Code Online (Sandbox Code Playgroud)
你可以dict.get
像这样简洁地写一样
>>> d = {'a': 1, 'b': 2}
>>> l = ['a', 'b', 'c', 'd', 'e']
>>> for item in l:
... d[item] = d.get(item, 0) + 1
>>> d
{'a': 2, 'c': 1, 'b': 3, 'e': 1, 'd': 1}
Run Code Online (Sandbox Code Playgroud)
dict.get
函数将查找该键,如果找到它将返回该值,否则它将返回您在第二个参数中传递的值.如果item
它已经是字典的一部分,那么将返回对它的数字,我们将1
其添加到它并将其存储回来item
.如果找不到,我们将得到0(第二个参数),我们将其加1并存储它item
.
现在,要获得总计数,您可以将函数中的所有值加起来sum
,就像这样
>>> sum(d.values())
8
Run Code Online (Sandbox Code Playgroud)
该dict.values
函数将返回字典中所有值的视图.在我们的例子中,它将编号,我们只是添加所有sum
功能.
归档时间: |
|
查看次数: |
10133 次 |
最近记录: |