我尝试迭代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中最后一行中列表的第一项对应的整数值?有没有其他更好的方法?在
正如Steve在评论中提到的,您的迭代器
student
将迭代来自hogwarts_students
('A','B','C',…)的键。这将导致if
语句中的键错误,因为它将尝试访问不存在的houses['A']
。在我建议使用
.items()
同时迭代hogwarts_students
的键和值,如下所示:另外,您还将此设置为一个接受
^{pr2}$students
参数的函数。如果students
将取代hogwarts_students
,那么请确保在函数中引用的是students
字典,而不是hogwarts_students
变量。在相关问题 更多 >
编程相关推荐