2

按照建议,我正在编写一个文本冒险游戏作为我的第一个 python 程序。我想要一张狗可能吃的东西的清单,它们有什么不好的,它们有多坏。所以,我想我会这样做:

badfoods = []
keys = ['Food','Problem','Imminent death']

food1 = ['alcohol', 'alcohol poisoning', 0]
food2 = ['anti-freeze', 'ethylene glycol', 1]
food3 = ['apple seeds', 'cyanogenic glycosides', 0] 

badfoods.append(dict(zip(keys,food1)))
badfoods.append(dict(zip(keys,food2))) 
badfoods.append(dict(zip(keys,food3))) 

实际上,我想包括大约 40 种食物。我知道我也可以这样做:

[{'Food':'alcohol', 'Problem':'alcohol poisoning', 'Imminent death':0},
 {'Food':'anti-freeze', 'Problem':'ethylene glycol', 'Imminent death':1}
 {'Food':'apple seeds, 'Problem':'cyanogenic glycosides', 'Imminent death':0}] ] 

我还在这里阅读了这篇关于使用 YAML 的文章,这很有吸引力: 实现嵌套字典的最佳方法是什么? 但我仍然不知道如何避免大量写键。

另外,我很生气,因为我无法弄清楚避免编写附加 40 次的原始方法,即:

def poplist(listname, keynames, name):
    listname.append(dict(zip(keynames,name)))

def main():
    badfoods = []
    keys = ['Food','Chemical','Imminent death']

    food1 = ['alcohol', 'alcohol poisoning', 0]  
    food2 = ['anti-freeze', 'ethylene glycol', 1]
    food3 = ['apple seeds', 'cyanogenic glycosides', 0]
    food4 = ['apricot seeds', 'cyanogenic glycosides', 0]
    food5 = ['avocado', 'persin', 0]
    food6 = ['baby food', 'onion powder', 0]

    for i in range(5):
        name = 'food' + str(i+1)
        poplist(badfoods, keys, name)

    print badfoods
main()

我认为它不起作用,因为我的 for 循环正在创建一个字符串,然后将其提供给函数,而函数 poplist 不将其识别为变量名。但是,我不知道是否有办法解决这个问题,或者我是否必须每次都使用 YAML 或写出密钥。任何帮助表示赞赏,因为我很难过!

4

3 回答 3

5

如果你一开始就把它做成一个单一的结构,那就更容易了。

foods = [
  ['alcohol', 'alcohol poisoning', 0],
  ['anti-freeze', 'ethylene glycol', 1],
  ['apple seeds', 'cyanogenic glycosides', 0],
  ['apricot seeds', 'cyanogenic glycosides', 0],
  ['avocado', 'persin', 0],
  ['baby food', 'onion powder', 0]
]
badfoods = [dict(zip(keys, food)) for food in foods]
于 2012-04-25T18:43:50.617 回答
4

你在附近:

>>> keys = ['Food','Chemical','Imminent death']
>>> foods = [['alcohol', 'alcohol poisoning', 0],
             ['anti-freeze', 'ethylene glycol', 1],
             ['apple seeds', 'cyanogenic glycosides', 0]]
>>> [dict(zip(keys, food)) for food in foods]
[{'Food': 'alcohol', 'Chemical': 'alcohol poisoning', 'Imminent death': 0}, {'Food': 'anti-freeze', 'Chemical': 'ethylene glycol', 'Imminent death': 1}, {'Food': 'apple seeds', 'Chemical': 'cyanogenic glycosides', 'Imminent death': 0}]
于 2012-04-25T18:43:46.630 回答
1

我建议遵循最佳实践并将数据与代码分开。只需使用最适合您需要的格式将您的数据存储在另一个文件中。从您到目前为止发布的内容来看,CSV 似乎是一个自然的选择。

# file 'badfoods.csv': 

Food,Problem,Imminent death
alcohol,alcohol poisoning,0
anti-freeze,ethylene glycol,1
apple seeds,cyanogenic glycosides,0

在您的主程序中,只需两行即可加载它:

from csv import DictReader

with open('badfoods.csv', 'r') as f:
    badfoods = list(DictReader(f))
于 2012-04-25T19:15:56.210 回答