2012-04-25 52 views
2

我正在按照建议编写一个文本冒险游戏作为我的第一个Python程序。我想列出一条狗可能吃的东西,它们有什么不好,以及它们有多糟糕。所以,我认为我是这么做的:使用zip的字典列表,将增量列表名称传递到函数

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,这是吸引人: What is the best way to implement nested dictionaries? 但我仍然没有看到如何避免写键一吨。

另外,我很生气,我不能找出我原来的方法来避免编写追加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() 

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

回答

3

你是附近:

>>> 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}] 
3

这是一个bleepton更容易,如果你只是让它摆在首位的单一结构。

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] 
0

我建议遵循最佳实践并将代码中的数据分开。只需使用最适合您需要的格式将数据存储在另一个文件中即可。从迄今为止发布的内容来看,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)) 
+0

这样的“最佳做法”的动机不强在Python中,他们真的做的语言,海事组织。 – 2012-04-25 19:31:57

+0

@KarlKnechtel:在任何语言中汇集代码和数据是一个糟糕的主意。看到这个问题的例子。 – georg 2012-04-25 19:55:38

相关问题