您的代码失败了,因为您试图修改正在迭代的列表,而不考虑副作用。你知道吗x = ['apple','fruit','orange','fruit','lemon','fruit']
for i in range(0,len(x),2):
if i%2 !=0:
x.pop(i)
print x
注1:range(0,len(x),2)将产生[0, 2, 4],并且没有一个会在条件下成功。所以,我假设你的意思是range(1,len(x),2)
注2:由于您在range(1,len(x),2)上迭代,实际上是[1, 3, 5],if条件已过时。你知道吗
当i为1时,我们将元素弹出为1。所以实际发生的是
在1处弹出元素之前x = ['apple','fruit','orange','fruit','lemon','fruit']
0 1 2 3 4 5
在1处弹出元素后x = ['apple','orange','fruit','lemon','fruit']
0 1 2 3 4
同样,当i变为3时,我们将元素放在3处
在3处弹出元素之前x = ['apple','orange','fruit','lemon','fruit']
0 1 2 3 4
在3处弹出元素后x = ['apple','orange','fruit','fruit']
0 1 2 3
现在,i变为5,位置5处没有元素。这就是x.pop(5)引发pop index out of range
错误。你可以用这个程序来确认x = ['apple','fruit','orange','fruit','lemon','fruit']
try:
for i in range(1,len(x),2):
if i%2 !=0:
x.pop(i)
except IndexError, e:
print e, x, i
输出是这样的pop index out of range ['apple', 'orange', 'fruit', 'fruit'] 5
解决方案
您可以使用切片表示法来仅获取偶数顺序数据中的元素,如下所示print x[::2] # ['apple', 'orange', 'lemon']
你可以得到奇数的元素,像这样print x[1::2] # ['fruit', 'fruit', 'fruit']
否则,您可以使用列表理解来过滤出奇数顺序数据,如下所示x = ['apple','fruit','orange','fruit','lemon','fruit']
print [item for idx, item in enumerate(x) if idx % 2 == 0]
# ['apple', 'orange', 'lemon']
print [item for idx, item in enumerate(x) if idx % 2 == 1]
# ['fruit', 'fruit', 'fruit']