遍历列表并删除python中某些元素的索引超出范围

问题描述 投票:-1回答:1

我正在尝试遍历2到10000的数字列表,并删除2、3、4和100的多义字符,但不删除这些数字,但是每次我删除一个项目时,列表的长度都会缩小,因此会产生索引越界错误我该如何解决?

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9xbDdoNC5wbmcifQ==” alt =“在此处输入图像描述”>

python loops indexoutofboundsexception
1个回答
0
投票

以下是一个可能适合您的示例。它利用列表理解。我不太了解您的代码,尤其是while循环中的索引增量,该增量仅运行到101。

def is_multiple(number):
    for m in range(2, 101):
        if number is not m and number % m == 0:
            return True


numbers = range(2, 10000)

numbers = [n for n in numbers if not is_multiple(n)]

print(numbers)
© www.soinside.com 2019 - 2024. All rights reserved.