2012-04-25 59 views
2

我正在按照建議編寫一個文本冒險遊戲作爲我的第一個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或寫出密鑰。任何幫助表示讚賞,因爲我很難過!

回答

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

這是一個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] 
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)) 
+0

這樣的「最佳做法」的動機不強在Python中,他們真的做的語言,海事組織。 – 2012-04-25 19:31:57

+0

@KarlKnechtel:在任何語言中彙集代碼和數據是一個糟糕的主意。看到這個問題的例子。 – georg 2012-04-25 19:55:38

相關問題