【问题标题】:keep getting 'list index out of range' while list is existing in python当python中存在列表时,继续获取“列表索引超出范围”
【发布时间】:2021-10-15 05:36:39
【问题描述】:

我试图将 @2@ 的最后一个元素放入 ,然后用它来设置 if 条件。但它只会给我带来“列表超出索引”的消息。以防万一,我尝试使用深层副本,但结果相同。

我想知道如何解决这个问题以及它发生的原因。

感谢您的帮助:)

import copy
    
animals = list(range(1,101))
new_animals = list()

#This below works fine
print(animals[-1])

for stage in range(1,8):
    if len(animals) <= 13 and len(animals) % 2 == 1:
        del animals[0]
    for number in animals[::2]:
        new_animals.append(number)
        
    print(new_animals)
    print(len(new_animals))
    
    animals = copy.deepcopy(new_animals)

    # @2@ This below is where I keep getting 'index out of range'
    last_animals = animals[-1]

    print(id(animals))
    print(id(new_animals))
    print()
    new_animals = list()

【问题讨论】:

  • 因为经过一些迭代,您的列表是空的
  • 问题是您正在重置 new_animals 列表。即 new_animals = list() 这会使列表为空,因此出现错误。

标签: python list indexing out


【解决方案1】:

在迭代过程中,您的动物已经用完了。 试试你的代码的这个变体,看看列表会发生什么。 调试的技巧是将print() 函数放在相关位置。

import copy
    
animals = list(range(1,101))
new_animals = list()

for _ in range(1,8):
    if len(animals) <= 13 and len(animals) % 2 == 1:
        del animals[0]
    for number in animals[::2]:
        new_animals.append(number)
    animals = copy.deepcopy(new_animals)
    print(animals)
    num_animals = len(animals)
    print(num_animals)
    if num_animals > 0:
        last_animals = animals[-1]

    new_animals = list()

结果是这样的:

# [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
# 50
# [1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61, 65, 69, 73, 77, 81, 85, 89, 93, 97]
# 25
# [1, 9, 17, 25, 33, 41, 49, 57, 65, 73, 81, 89, 97]
# 13
# [9, 25, 41, 57, 73, 89]
# 6
# [9, 41, 73]
# 3
# [41]
# 1
# []
# 0

【讨论】:

    猜你喜欢
    • 2021-06-01
    • 1970-01-01
    • 2014-02-24
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多