apr*_*ash 2 python zip dictionary list
我正在按照建议编写一个文本冒险游戏作为我的第一个 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)))
Run Code Online (Sandbox Code Playgroud)
实际上我想包括大约 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}] ]
Run Code Online (Sandbox Code Playgroud)
我还在这里阅读了有关使用 YAML 的这篇文章,这很吸引人:实现嵌套字典的最佳方法是 什么? 但我仍然不知道如何避免大量写入密钥。
另外,我很恼火,我无法弄清楚避免编写 append 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()
Run Code Online (Sandbox Code Playgroud)
我认为它不起作用,因为我是 for 循环正在创建一个字符串,然后将其提供给函数,而函数 poplist 无法将其识别为变量名。但是,我不知道是否有办法解决这个问题,或者我是否必须每次都使用 YAML 或写出密钥。任何帮助表示赞赏,因为我很难过!
如果您首先将其设为单一结构,则它会更容易使用 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]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1553 次 |
最近记录: |