一个简单的python列表程序得到索引错误

时间:2015-09-15 07:28:20

标签: python python-3.x

很抱歉提出这个问题。这是一个简单的python程序

odd = lambda x : bool(x % 2)
numbers = [n for n in range(10)]
print numbers
for i in range(len(numbers)):
    if numbers[i]%2!=0:
        del numbers[i]
    print numbers

运行此程序时出错 Traceback (most recent call last): File "test.py", line 5, in <module> if numbers[i]%2!=0: IndexError: list index out of range

我尝试了很多东西,但没有任何工作,任何人都可以帮助我

3 个答案:

答案 0 :(得分:3)

备注:

如果你真的NEED TO DELETE THE LIST WHEN LOOPING你可以反向循环列表并删除元素它将不会停止迭代,因为它将在正常方向删除元素(左 - >右)并且循环在相反方向(右 - >左)

<强>代码:

odd = lambda x : bool(x % 2)
numbers = [n for n in range(10)]
print numbers
for i in numbers[::-1]:
    print i
    if i%2!=0:
        del numbers[numbers.index(i)]
print numbers

<强>输出:

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

或者更简单一点list comprehension and your lambda function

<强>代码1:

[num for num in numbers if not odd(num)]

<强>输出1:

 [0, 2, 4, 6, 8]

答案 1 :(得分:2)

b = range(10)
a = [i for i in b if not i%2]

print a

答案 2 :(得分:1)

 odd = lambda x : bool(x % 2)
    numbers = [n for n in range(10)]
    print numbers
    for i in range(len(numbers)):
        try:
            if numbers[i]%2!=0:
               del numbers[i]
                print numbers
        except IndexError:
            pass