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

2024-09-28 22:25:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个文本冒险游戏作为我的第一个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种食物。我也知道:

^{pr2}$

我也在这里读到了这篇关于使用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或写出密钥。我被难住了,任何帮助都是感激的!在


Tags: namefoodkeyszipdictappendseedsalcohol
3条回答

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

# file 'badfoods.csv': 

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

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

^{pr2}$

如果你一开始就把它变成一个单一的结构,那就更简单了。在

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]

你在附近:

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

相关问题 更多 >