【问题标题】:Indexing Variables with Loops使用循环索引变量
【发布时间】: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


【解决方案1】:

我可以从您的代码中了解到,您正在尝试从键(标题)列表和列表列表中创建字典。

在 python 中,您可以使用函数 zip() 来执行此操作。在您的情况下,它看起来像这样:


def list_to_dict(titles, nested_list):
    nobel_awards = {}
    for award in nested_list:
        year_category = dict(zip(titles, award))
        nobel_awards[year_category['name']] = year_category
    return nobel_awards


nested_list = [['Test', 'title'], ['test2', 'title2']]
titles = ['name', 'title']
result = list_to_dict(titles, nested_list)

print(result)

结果如下所示:

{'Test': {'name': 'Test', 'title': 'title'}, 'test2': {'name': 'test2', 'title': 'title2'}}

【讨论】:

    【解决方案2】:

    据我了解,您使用列表的值而不是列表的索引访问列表。您可以在循环中使用enumerate() 函数并将i 变量替换为列表的索引。例如:

    for index, value in enumerate(nested_list):
        ''' Your code here '''
        year_category[titles[1]] = nested_list[index][1] #sample
        ...
    

    我不知道这两个参数的内容是什么样的,但是错误“列表索引必须是整数,切片器”将通过索引访问列表来解决,就像上面的示例一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-13
      • 2011-02-19
      • 2021-04-13
      • 1970-01-01
      • 2019-07-05
      • 2012-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多