在字典值中解包元组



我有一个嫌疑犯元组,嫌疑犯存在于字典和字典中我有一个元组值

我尝试将值解包到变量

suspects = (
{'name': 'Anne', 'evidences': ('derringer', 'Caesarea')},
{'name': 'Taotao', 'evidences': ('derringer', 'Petersen House')},
{'name': 'Pilpelet', 'evidences': ('Master Sword', 'Hyrule')},
)
for t in suspects:
for name, weapon,location in t.items():

我被压扁了。我试着运行python教程来查看我的错误反馈,但我不明白如何提取具体的值带拆包方案

为示例解决方案:姓名= Anne,武器= Derringer,地点= Caesarea

可以这样做:

for t in suspects:
weapon, location = t["evidences"]
print(f"Name: {t['name']} Weapon: {weapon} Location: {location}")

试试这个:

suspects = (
{'name': 'Anne', 'evidences': ('derringer', 'Caesarea')},
{'name': 'Taotao', 'evidences': ('derringer', 'Petersen House')},
{'name': 'Pilpelet', 'evidences': ('Master Sword', 'Hyrule')},
)
for t in suspects:
name = t['name']
weapon, location = t['evidences']
print(name, weapon, location)

输出:

Anne derringer Caesarea
Taotao derringer Petersen House
Pilpelet Master Sword Hyrule

编辑:如果你必须解压两次,这里有一个更难看的方法,解压两次(键,值)和(武器,位置):

suspects = (
{'name': 'Anne', 'evidences': ('derringer', 'Caesarea')},
{'name': 'Taotao', 'evidences': ('derringer', 'Petersen House')},
{'name': 'Pilpelet', 'evidences': ('Master Sword', 'Hyrule')},
)
for t in suspects:
name = None
weapon = None
location = None
for key, value in t.items():
if key == "name":
name = value
elif key == "evidences":
weapon, location = value
print(name, weapon, location)

您的数据结构不利于您想要做的事情。如果您想要保留这种特定结构有特定的原因,那么请使用所提供的答案。但是,如果您愿意使用不同的数据结构:

suspects = {"Anne": ("derringer", "Caesarea"),
"Taotao": ("derringer", "Petersen House"),
"Pilpelet": ("Master Sword", "Hyrule")}
for name, (weapon, location) in suspects.items():
print(name, weapon, location)

输出:

Anne derringer Caesarea
Taotao derringer Petersen House
Pilpelet Master Sword Hyrule

相关内容

  • 没有找到相关文章

最新更新