使用zip的字典列表,将增量列表名称传递给函数

时间:2012-04-25 18:35:55

标签: python list dictionary zip

我正在编写一个文本冒险游戏作为我建议的第一个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的帖子,这很有吸引力: 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()

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

3 个答案:

答案 0 :(得分: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}]

答案 1 :(得分:3)

如果你只是把它作为一个单一的结构,那么它就更容易了。

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]

答案 2 :(得分: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))