我实际上甚至不确定我需要一本字典我只是不确定还能做什么。基本上我需要将用户输入乘以多个值。这就是我正在使用的。
SmallItalian = {"Loaf of bread": .5, "Salami": .3, "Vegetables": .2, "Slices of cheese": 4}
s_italian = input("How many small Italians were sold?")
我需要将它们相乘以便接收类似输出的内容:
You have used ..
16.5 loaves of bread
1.3 lbs of Salami
7.5 lbs of Veges
142 slices of Cheese
7.4 lbs of Turkey
编辑:所以我有
for amount in SmallItalian.values():
print(SmallItalian)
我现在如何将输入乘以字典值?
答案 0 :(得分:0)
您可以通过它的键,它的值或两者的组合(它的项目)来遍历字典。只需使用
for ingredient in Smallitalian.keys():
或
for amount in Smallitalian.values():
或
for ingredient, amount in Smallitalian.items():
并在循环中使用相应的变量。然后它应该变得微不足道。
在这个用例中使用字典似乎没问题。
答案 1 :(得分:0)
我不确定你是否想要将字典中的每个项目乘以相同的数字,而不是说清楚。如果你想要实现这一目标,这是另一种方法:
SmallItalian = {"Loaf of bread": .5, "Salami": .3, "Vegetables": .2, "Slices of cheese": 4}
value = input("How many small Italians were sold? ")
print "You have used..."
for item in SmallItalian:
SmallItalian[item] = SmallItalian[item] * value
print "{} {}".format(item, SmallItalian[item])
答案 2 :(得分:0)
如果由于某种原因你需要保留SmallItalian
,你可以试试这个:)
SmallItalian = {"Loaf of bread": .5, "Salami": .3, "Vegetables": .2, "Slices of cheese": 4}
outputMapping = {"Loaf of bread": "loaves of bread",
"Salami": "lbs of Salami",
"Vegetables": "lbs of Veges",
"Slices of cheese": "slices of Cheese"}
# need to int() it as input by default is a string
s_italian = int(input("How many small Italians were sold?"))
print("You have used ..")
# go through SmallItalian
for item, qty in SmallItalian.items():
print(round(s_italian*qty,1), outputMapping[item])
# round to 1d.p.
Python shell的输出
How many small Italians were sold?6
You have used ..
3.0 loaves of bread
1.8 lbs of Salami
1.2 lbs of Veges
24 slices of Cheese
>>>
for item, qty in SmallItalian.items():
将遍历SmallItalian
字典,其中item
是关键字,qty
是值
请告诉我这是否是您要找的内容:)