【问题标题】:Python: list inside a list index out of range errorPython:列表内的列表索引超出范围错误
【发布时间】:2012-11-21 11:30:38
【问题描述】:

尝试将值附加到列表中的列表时出现错误。我做错了什么?

xRange = 4
yRange = 3
baseList = []
values = []
count = 0

#make a list of 100 values
for i in range(100):
    values.append(i)

#add 4 lists to base list
for x in range(xRange):
    baseList.append([])
#at this point i have [[], [], [], []]

#add 3 values to all 4 lists
    for x in range(xRange):
        for y in range(yRange):
            baseList[x][y].append(values[count])
            count += 1

print baseList

#the result i'm expecting is:
#[[0,1,2], [3,4,5], [6,7,8], [9,10,11]]

我收到此错误:

Traceback (most recent call last):
  File "test.py", line 19, in <module>
    baseList[x][y].append(values[count])
IndexError: list index out of range

【问题讨论】:

  • 附带说明,您可以创建一个 n 空列表列表,如下所示:baseList = [[]] * n。不需要显式循环。
  • @Iguananaut - 这将创建对同一个列表的多个引用,因此当您修改一个时,它们都会受到影响。这是一个常见的错误。
  • 啊,当然。好尴尬!

标签: python list indexing range


【解决方案1】:

您不应将索引编入空列表。您应该在列表本身上调用append

改变这个:

baseList[x][y].append(values[count])

到这里:

baseList[x].append(values[count])

结果:

[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]

在线查看:ideone

【讨论】:

    【解决方案2】:
    for x in range(xRange):
        baseList.append([])
    # at this point i have [[], [], [], []]
    

    对,baseList = [[], [], [], []]。因此,访问baseList[0][0] 将失败,因为第一个子列表没有元素。

    顺便说一句。使用itertoolsrecipes 可以更轻松地获得通缉名单。

    >>> x = 4
    >>> y = 3
    >>> list(itertools.islice(zip(*([itertools.count()] * y)), x))
    [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)]
    

    这基本上是从 0 开始的不定 count 的 y-grouper 的 x-take

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-06
      • 2014-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-12
      • 1970-01-01
      相关资源
      最近更新 更多