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

2024-03-28 15:22:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试迭代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中最后一行中列表的第一项对应的整数值?有没有其他更好的方法?在


Tags: 项目字符串列表整数studentchoicestudentsdict1
1条回答
网友
1楼 · 发布于 2024-03-28 15:22:43

正如Steve在评论中提到的,您的迭代器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变量。在

^{pr2}$

相关问题 更多 >