小编apr*_*ash的帖子

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

我正在按照建议编写一个文本冒险游戏作为我的第一个 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', …
Run Code Online (Sandbox Code Playgroud)

python zip dictionary list

2
推荐指数
1
解决办法
1553
查看次数

标签 统计

dictionary ×1

list ×1

python ×1

zip ×1