【问题标题】:What happens when we a negative value in python's for loop?当我们在python for循环中为负值时会发生什么?
【发布时间】:2020-04-18 14:18:32
【问题描述】:
x = 10
l = [1]
for i in range(x):
    # Modified v
    print("Row", i + 1, l)
    newlist = []
    newlist.append(l[0])
    for i in range(len(l) - 1):
        newlist.append(l[i] + l[i+1])
    newlist.append(l[-1])
    l = newlist

我不明白当索引变为负数时会发生什么

【问题讨论】:

  • 这段代码的目标是什么?问题出在哪里(=哪一行)?请添加更多详细信息。

标签: python loops for-loop indexing


【解决方案1】:

当您给出负索引时,返回该索引处的值。对于列表 a=[1,2,3]

我们可以说

value 1 is at index 0
value 2 is at index 1
value 3 is at index 2

value 3 is at index -1
value 2 is at index -2
value 1 is at index -3

如果你超出这个索引范围,在这种情况下是负 3 到正 3,你会得到 ​​p>

IndexError: list index out of range

对于您的代码,第二个 for 块永远不会执行,因此您不会看到索引错误。

x = 10
l = [1]
for i in range(x):
  print("Row", i + 1, l)

newlist = []

newlist.append(l[0])


# Length l is 0,so below code inside for is never executed as range is empty
for i in range(len(l) - 1):
    newlist.append(l[i] + l[i+1])
    newlist.append(l[-1])
    l = newlist

【讨论】:

    猜你喜欢
    • 2018-06-15
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 2013-07-29
    • 2018-09-01
    • 1970-01-01
    • 2011-11-01
    • 1970-01-01
    相关资源
    最近更新 更多