[英]Python delete every third element from the list
x = [1,2,3,4,5,6,7,8,9,10]
for i in range(len(x)):
if i%3==0:
x.pop(i)
print(x)
so i want to get this所以我想得到这个
[2,3,5,6,8,9]
instead i get error x.pop(i) out of range I know there is simpler way to do this, but i have to do this with for loop相反,我得到错误 x.pop(i) out of range 我知道有更简单的方法可以做到这一点,但我必须用 for 循环来做到这一点
Short and simple:简短而简单:
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> del x[::3]
>>> x
[2, 3, 5, 6, 8, 9]
The problem with the loop is that after you call pop
, the i
th element isn't the same as before the call.循环的问题在于,在您调用
pop
,第i
个元素与调用之前不同。
>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> x[3]
4
>>> x.pop(0)
>>> x[3]
5
You can mitigate this by working from the other end of the list.您可以通过从列表的另一端工作来缓解这种情况。
for i in range(len(x)-1, -1, -1):
if i % 3 == 0:
x.pop(i) # or del x[i]
You are getting that because you are resizing the x
list while iterating over it, not advisable.您之所以这样做,是因为您在迭代时调整了
x
列表的大小,这是不可取的。 You should create another list with the values filtered, like this:您应该使用过滤的值创建另一个列表,如下所示:
x = [1,2,3,4,5,6,7,8,9,10]
output = []
for i, v in enumerate(x):
if i % 3:
output.append(v)
print(output)
>>> [2, 3, 5, 6, 8, 9]
As others have pointed out you're removing elements from the list whilst you are iterating over it.正如其他人指出的那样,您正在迭代列表时从列表中删除元素。
Since you said you have to use a for
loop I'd suggest a list comprehension:既然你说你必须使用
for
循环,我建议你使用列表理解:
l = [v for i, v in enumerate(x) if i % 3 != 0]
print(l)
This error is because of using len(x) instead of len(x)-1.此错误是因为使用 len(x) 而不是 len(x)-1。 But the code you wrote down doesn't output the desired result you look for.
但是你写下的代码并没有输出你想要的结果。
Try this:尝试这个:
x = [1,2,3,4,5,6,7,8,9,10]
y = []
for i in range(len(x)-1):
if i%3==0:
continue;
else:
y.append(x[i])
print(y)
You are getting an error because your len(x)
is decrementing each time you remove the element, whereas the value of i is not changing wrt the new len(x)
.您会收到错误消息,因为每次删除元素时
len(x)
都会递减,而 i 的值并没有改变新的len(x)
。
You can check this by adding print()
statements.您可以通过添加
print()
语句来检查这一点。
Adding those statements, your code is now :添加这些语句,您的代码现在是:
x = [1,2,3,4,5,6,7,8,9,10]
for i in range(len(x)):
if i%3==0:
print("Before \n i:",i, "len : ",len(x))
x.pop(i)
print("After \n i:",i, "len : ",len(x))
print(x)
This is your stack trace :这是您的堆栈跟踪:
Before
i: 0 len : 10
After
i: 0 len : 9
Before
i: 3 len : 9
After
i: 3 len : 8
Before
i: 6 len : 8
After
i: 6 len : 7
Before
i: 9 len : 7
Traceback (most recent call last):
File "q.py", line 6, in <module>
x.pop(i)
IndexError: pop index out of range
You can make the following change to the code to get your output :您可以对代码进行以下更改以获取输出:
x = [i for i in range(1,11)]
del x[::3]
print(x)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.