【发布时间】:2017-11-27 14:59:32
【问题描述】:
我正在尝试编写代码以将材料分发给不同的组。为此,我想使用字典。但是我需要使用 if 和 for 循环来匹配条件,我怀疑问题是这些条件的输出是字符串,因此它们不会引用字典(错误类型)。我事先不知道该调用哪个字典,所以我也无法具体写下来。
让我进一步阐述我的问题。我的情况可以简化为:我有一家水果店,我想做水果篮。我想在每个篮子里放尽可能多的水果。我今天有新的水果供应,但篮子里已经有昨天的水果了。
我做的第一件事是找出每个篮子从昨天开始有多少水果。我拥有的数据(作为 csv 文件)是这样的。
Fruit Basket
'apple' '1'
'apple' '2'
'apple' '4'
'orange' '4'
'melon' '1'
...
所以我创建了空字典。
basket1 = {'total':0, 'max':5, 'apple':0, 'banana':0, 'melon':0, 'orange':0,'other':0}
basket2 = {'total':0, 'max':5, 'apple':0, 'banana':0, 'melon':0, 'orange':0,'other':0}
...
所以我的伪代码:
for i in range (number of rows in csv file):
temp = fruit in i-th row # this is a string which I hope to use as key
for j in range(number of baskets):
if basket of the i-th fruit == basket j
assignedBasket = 'basket'+'j' # this is to call the right dictionary
assignedBasket[temp] += 1 # add 1 to the correct key
我认为问题在于assignedBasket 是一个字符串,而不是字典。如何访问正确的字典?任何帮助将不胜感激。谢谢!
【问题讨论】:
-
number of rows in csv file,你的代码在运行吗?您的代码中有很多语法错误。 -
你缺少(至少)一些冒号...
-
对不起,这是伪代码,我会更新它。
-
How do I create a variable number of variables? 的可能重复项...也许将您的字典保存在字典中,然后您可以构造字符串以匹配键。
标签: python python-3.x dictionary