【问题标题】:Accessing a specific dictionary using if statement (string to dictionary conversion)使用 if 语句访问特定字典(字符串到字典的转换)
【发布时间】: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


【解决方案1】:

您不想为basket1basket2 等设置单独的变量。你想要一个列表的字典。

baskets = [ {'total':0, 'max':5, 'apple':0, 'banana':0, 'melon':0, 'orange':0,'other':0},
            {'total':0, 'max':5, 'apple':0, 'banana':0, 'melon':0, 'orange':0,'other':0},
            ... ]

然后要访问第 j 个篮子,只需调用 baskets[j]。请注意,编写循环的更惯用的方法不是for j in range(len(baskets)),而是for basket in baskets

根据我的经验,这是第一次开始编码时遇到的一个相当常见的问题。如果您发现自己想用 1、2 等标记变量,并且想根据它们的标签来调用它们,那么您真的需要一个数组。当您真的只需要使用一个类时,它与尝试同时保持多个相互平行的列表的奇怪常见策略相吻合。

【讨论】:

  • 非常感谢!
猜你喜欢
  • 2016-04-08
  • 1970-01-01
  • 1970-01-01
  • 2017-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-21
相关资源
最近更新 更多