假设我有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
相反,我得到:
1 a
2 b
1 c
1 d
1 e
Total number of items: 6
到目前为止我所拥有的:
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)
任何帮助将不胜感激!
答案 0 :(得分:6)
你只需要迭代列表并在密钥已经存在的情况下递增计数,否则将其设置为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}
您可以使用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}
dict.get
函数将查找该键,如果找到它将返回该值,否则它将返回您在第二个参数中传递的值。如果item
已经是字典的一部分,那么将返回针对它的数字,我们会向其添加1
并将其存储回相同的item
。如果找不到,我们将得到0(第二个参数),我们将其加1并将其存储在item
。
现在,要获得总计数,您只需将sum
函数添加到字典中的所有值,就像这样
>>> sum(d.values())
8
dict.values
函数将返回字典中所有值的视图。在我们的例子中,它将编号,我们只需添加sum
函数。
答案 1 :(得分:2)
另一种方式:
使用集合模块:
>>> import collections
>>> a = {"a": 10}
>>> b = ["a", "b", "a", "1"]
>>> c = collections.Counter(b) + collections.Counter(a)
>>> c
Counter({'a': 12, '1': 1, 'b': 1})
>>> sum(c.values())
14
答案 2 :(得分:1)
使用collections.Counter
,因为它拥有您手头任务所需的一切:
from collections import Counter
the_list = ['a', 'b', 'c', 'd', 'e']
counter = Counter({'a': 1, 'b': 2})
counter.update(the_list)
for c in sorted(counter):
print c, counter[c]
为了获得总计数,您可以简单地将counter
:
sum(counter.values())
# 8
答案 3 :(得分:1)
stuff={'rope':1,'torch':6,'gold coin':42,'dagger':1,'arrow':12}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def displayInventory(inventory):
print('Inventory:')
item_total=0
for k,v in inventory.items():
print(str(v)+' '+k)
item_total=item_total+v
print('Total number of items: '+ str(item_total))
def addToInventory(inventory,addedItems):
for v in addedItems:
if v in inventory.keys():
inventory[v]+=1
else:
inventory[v]=1
addToInventory(stuff,dragonLoot)
displayInventory(stuff)
答案 4 :(得分:1)
如果您正在寻找使用Python自动化无聊内容的列表到幻想游戏库的字典功能的解决方案,这里有一个有效的代码:
# inventory.py
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
#this part of the code displays your current inventory
def displayInventory(inventory):
print('Inventory:')
item_total = 0
for k, v in inventory.items():
print(str(v) + ' ' + k)
item_total += v
print("Total number of items: " + str(item_total))
#this launches the function that displays your inventory
displayInventory(stuff)
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
# this part is the function that adds the loot to the inventory
def addToInventory (inventory, addedItems):
print('Your inventory now has:')
#Does the dict has the item? If yes, add plus one, the default being 0
for item in addedItems:
stuff[item] = stuff.get(item, 0) + 1
# calls the function to add the loot
addToInventory(stuff, dragonLoot)
# calls the function that shows your new inventory
displayInventory(stuff)
答案 5 :(得分:1)
关于幻想游戏库存的字典功能列表的问题' - 第5章用Python自动化无聊的东西。
# This is an illustration of the dictionaries
# This statement is just an example inventory in the form of a dictionary
inv = {'gold coin': 42, 'rope': 1}
# This statement is an example of a loot in the form of a list
dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
# This function will add each item of the list into the dictionary
def add_to_inventory(inventory, dragon_loot):
for loot in dragon_loot:
inventory.setdefault(loot, 0) # If the item in the list is not in the dictionary, then add it as a key to the dictionary - with a value of 0
inventory[loot] = inventory[loot] + 1 # Increment the value of the key by 1
return inventory
# This function will display the dictionary in the prescribed format
def display_inventory(inventory):
print('Inventory:')
total_items = 0
for k, v in inventory.items():
print(str(v) + ' ' + k)
total_items = total_items + 1
print('Total number of items: ' + str(total_items))
# This function call is to add the items in the loot to the inventory
inv = add_to_inventory(inv, dragon_loot)
# This function call will display the modified dictionary in the prescribed format
display_inventory(inv)
答案 6 :(得分:1)
invent = {'rope': 1, 'torch':6, 'gold coin': 42, 'dagger':1, 'arrow':12}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def displayInventory(weapons):
print('Inventory')
total = 0
for k, v in weapons.items():
print(str(v), k)
total += v
print('Total number of items: ' + str(total))
def addToInventory(inventory, addedItems):
for item in addedItems:
inventory.setdefault(item, 0)
inventory[item] = inventory[item] + 1
return(inventory)
displayInventory(addToInventory(invent, dragonLoot))
答案 7 :(得分:1)
对于您的问题的第一部分,要将列表项添加到字典中,我使用了以下代码:
import numpy as np
import tensorflow as tf
a = np.array([[1,2,3,4],[4,3,2,1],[1,2,3,4],[4,3,2,1]])
w = np.array([[5,4,3],[3,4,5],[5,4,3]])
# We make weights to a 6x6 matrix by repeating 2 times on both axis
w_rep = np.repeat(w,2,axis=0)
w_rep = np.repeat(w_rep,2,axis=1)
# Let's now jump in to tensorflow
tf_a = tf.constant(a)
tf_w = tf.constant(w_rep)
tf_segments = tf.constant([0,1,1,2,2,3])
# This is the most tricky bit, here we use the segment_sum to achieve what we need
# You can use segment_sum to get the sum of segments on the very first dimension of a matrix.
# So you need to do that to the input matrix twice. One on the original and the other on the transpose.
tf_w2 = tf.math.segment_sum(tf_w, tf_segments)
tf_w2 = tf.transpose(tf_w2)
tf_w2 = tf.math.segment_sum(tf_w2, tf_segments)
tf_w2 = tf.transpose(tf_w2)
print(tf_w2*a)
我之所以分享它,是因为我将inventory = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def addToInventory(inventory, addedItems):
for i in addedItems:
if i in inventory:
inventory[i] = inventory[i] + 1
else:
inventory[i] = 1 #if the item i is not in inventory, this adds it
# and gives the value 1.
函数的if
语句设置用作其他注释。现在,我离开了.get
,它似乎比我的代码更简单,更短。但是,在我遇到此练习的一本书“使无聊的东西自动化”一章中,我还没有学到(或不够好).get
函数。
对于显示清单的功能,我具有与其他注释相同的代码:
.get
我调用了两个函数,结果如下:
def displayInventory(inventory):
print('Inventory:')
tItems = 0
for k, v in inventory.items():
print(str(v) + ' ' + k)
for v in inventory.values():
tItems += v
print()
print('Total of number of items: ' + str(tItems))
我希望这会有所帮助。
答案 8 :(得分:0)
$search = 'Roofing';
foreach($array as $item) {
if (strpos($item, $search) !== 0) {
// entry found
}
}
答案 9 :(得分:0)
对于这个问题的第一部分,这是我想出的代码。
invt = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
print ("Inventory:")
total = sum(invt.values())
for x, v in invt.items():
print (str(v) + ' ' + x)
print ("Total number of items: {}".format(total))
我看到大多数人都在通过循环进行交互以添加到总变量中。然而,使用sum方法,我跳过了一步..
始终愿意接受反馈......
答案 10 :(得分:0)
下面是使用上述技巧的代码,以及名词的复数形式略有不同。对于那些愿意和勇敢的人,有ifs和elifs作为例外的任务;)
# sets your dictionary
backpack = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
# this function display your current inventory
def displayInventory(inventory):
print("Backpack:")
itemTotal = 0
for k, v in inventory.items():
# creates a simple plural version of the noun
# (adds only the letter "s" at the end of the word) does not include exceptions
# (for example, torch - 'torchs' (should be 'torches'), etc.
if v > 1:
print(str(v) + ' ' + k +'s')
else:
print(str(v) + ' ' + k)
itemTotal += v
print("Total quantity of items: " + str(itemTotal))
# sets your loot
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
# this function adds your loot to your inventory
def addToInventory(inventory, addedItems):
for item in addedItems:
inventory[item] = inventory.get(item,0) + 1
# launch your functions
addToInventory(backpack, dragonLoot)
displayInventory(backpack)