【发布时间】:2020-03-03 03:03:58
【问题描述】:
在我的代码中,我尝试通过在列出的列表和嵌套列表(两个单独的输入)中索引值来将值插入字典。
def list_to_dict(titles, nested_list):
nobel_awards = {}
index = 0
for i in nested_list:
year_category = {}
year_category[titles[1]] = nested_list[i][1]
year_category[titles[2]] = nested_list[i][2]
nobel_awards[nested_list[i][0]] = year_category
return nobel_awards
它返回一个错误,指出“列表索引必须是整数,切片器”
我很困惑为什么。
【问题讨论】:
-
你有数据示例吗?
-
您能否向我们展示嵌套列表的外观以及您要完成的工作。这样,可以更轻松地帮助您改进代码并使其正常工作。
-
发生错误是因为您将某些内容放入
[],而不是整数或切片器。所以参数中的数据很重要。 -
nested_list[i][1]→i[1]? -
当您将这些嵌套列表“值”分配给实际字典“值”时,您也不能像那样分配字典的键。并且通过使用无效的可迭代列表来遍历列表中的列表不是pythonic。
标签: python list loops for-loop indexing