我正在按照建議編寫一個文本冒險遊戲作爲我的第一個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或寫出密鑰。任何幫助表示讚賞,因爲我很難過!
這樣的「最佳做法」的動機不強在Python中,他們真的做的語言,海事組織。 – 2012-04-25 19:31:57
@KarlKnechtel:在任何語言中彙集代碼和數據是一個糟糕的主意。看到這個問題的例子。 – georg 2012-04-25 19:55:38