繁体   English   中英

Python:如何使用每个列表上的索引 0 从列表字典中访问字典中的字符串键?

[英]Python: How to access string key in dictionary from a dictionary of lists using index 0 on each list?

我正在尝试遍历 dict1,它具有两个项目列表的键,字符串。 还有一个有四个条目的字典 (dict2)。 这些条目的键是 dict1 中列表中唯一可能的四个字符串。 当我遍历 dict1 时,我希望程序挑选出列表中的第一项,然后在 dict2 中找到该键,这样我就可以根据我遍历的内容访问它们的整数值。 字符串是相同的,所以如果正确访问它应该可以工作吗? 这是我的代码:

hogwarts_students = { "A" : ["Gryffindor", "Slytherin"],"B" : ["Hufflepuff", "Ravenclaw"],"C" : ["Ravenclaw", "Hufflepuff"],"D" : ["Slytherin", "Ravenclaw"]}
top_choice = 0
second_choice = 0
no_choice = 0
houses = {"Gryffindor" : 0, "Hufflepuff" : 0, "Ravenclaw" : 0,
"Slytherin" : 0}
def sorting_hat(students):
    for student in hogwarts_students:
        if houses[student][0] <= len(hogwarts_students) / 4:

我是否在最后一行正确访问与 dict1 中列表的第一项对应的整数值? 有没有其他更好的方法来做到这一点?

正如史蒂夫在他的评论中提到的,您的迭代器student将迭代来自hogwarts_students的键('A'、'B'、'C'、...)。 这将导致if语句中出现关键错误,因为它将尝试访问不存在的houses['A']

我建议使用.items()同时迭代hogwarts_students的键和值,例如:

for student, house_options in hogwarts_students.items():
    first_option = house_options[0]
    if houses[first_option] <= len(hogwarts_students) // 4:
        # Do something
        pass

此外,您将此设置为采用students参数的函数。 如果students要代替hogwarts_students那么请确保您在函数中引用students字典而不是hogwarts_students变量。

def sorting_hat(students):
    for student, house_options in students.items():
        first_option = house_options[0]
        if houses[first_option] <= len(students) // 4:
            # Do something
            pass

暂无
暂无

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

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