【问题标题】:Index out of Range despite check尽管检查,索引超出范围
【发布时间】:2020-09-03 02:30:44
【问题描述】:
    t = [1, 2, 3]
def cumsum(t):
    t2 = []
    total = 0
    i = 0
    while i < len(t): 
        total += t[i]
        t2[i].append(total)
        i += 1
    return t2

cumsum(t)

此代码获取前两个列表整数的总和并将其附加到另一个列表。 我觉得这在逻辑上应该可行,我不明白为什么当 len(t)= 3 时 i

【问题讨论】:

  • 从此行t2[i].append(total) 删除[i]t2 开头是空列表,因此使用 0 对其进行索引会产生 IndexError。
  • 要将元素附加到 t2 您不需要按索引引用它。只做 t2.append(total)
  • t2[i] 不存在,只追加不索引。
  • 另外,到appendt2[i]t2[i] 本身必须是一个列表。如果t2[i] 已经存在,则必须使用t2[i] = total 更改其值。
  • 换句话说,您检查 i 是 t 的有效索引,但 不是 t2。

标签: python indexing range


【解决方案1】:

因为您使用索引i 来访问为空的t2 列表。要将元素附加到列表中,您应该使用&lt;list&gt;.append(&lt;element&gt;),在您的情况下为t2.append(total)

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 2020-08-18
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    相关资源
    最近更新 更多