简体   繁体   English

在字典值中解包元组

[英]Unpacking Tuple in Dictionary Value

i have a tuple of suspects those suspects exist in dictionary and in the dictionary i have a tuple value我有一个嫌疑人元组,这些嫌疑人存在于字典中,在字典中我有一个元组值

i try to unpacking the values to varibles我尝试将值解压缩为变量

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():

there i got stacked.我被堆积了。 i try to run python tutor to see a feeback of my faults, but i can't understand how can i extract the specific value with unpacking solution我尝试运行 python 导师来查看我的错误反馈,但我不明白如何通过解包解决方案提取特定值

for examp solution: Name = Anne, Weapon = Derringer, Location = Caesarea例如解决方案:Name = Anne,Weapon = Derringer,Location = Caesarea

Try this on for size:试穿这个尺寸:

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)

Output: Output:

Anne derringer Caesarea
Taotao derringer Petersen House
Pilpelet Master Sword Hyrule

EDIT: If you must unpack twice, here's an uglier way to do it that does unpack twice (key, value) and (weapon, location):编辑:如果您必须解包两次,这是一种更丑陋的方法,可以解包两次(键,值)和(武器,位置):

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)

This would be the way to do it:这将是这样做的方法:

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

Your data structure isn't conducive to what you're trying to do exactly.您的数据结构不利于您正在尝试做的事情。 If there's a specific reason why you want to keep this particular structure, then use the answers provided.如果有特定原因要保留此特定结构,请使用提供的答案。 If, however, you're open to using a different data structure:但是,如果您愿意使用不同的数据结构:

suspects = {"Anne": ("derringer", "Caesarea"),
            "Taotao": ("derringer", "Petersen House"),
            "Pilpelet": ("Master Sword", "Hyrule")}

for name, (weapon, location) in suspects.items():
    print(name, weapon, location)

Output: Output:

Anne derringer Caesarea
Taotao derringer Petersen House
Pilpelet Master Sword Hyrule

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM