我正在写一个文本冒险游戏作为我的第一个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或写出密钥。我被难住了,任何帮助都是感激的!在
我建议遵循最佳实践并将数据从代码中分离出来。只需使用最适合您需要的另一种格式存储数据。从你目前发布的内容来看,CSV似乎是一个自然的选择。在
在主程序中,只需两行即可加载:
^{pr2}$如果你一开始就把它变成一个单一的结构,那就更简单了。在
你在附近:
相关问题 更多 >
编程相关推荐