Python:如何从列表中删除/删除第n个元素? [英] Python: how to remove/delete every n-th element from list?
问题描述
我已经看过这篇文章: Python:从现有的列表中构建新列表删除每个第n个元素,但由于某种原因,它对我不起作用:
我尝试过这种方式:
def drop(mylist, n):
del mylist[0::n]
print(mylist)
此功能获取一个列表和一个n
.然后,它使用列表中的n步删除每个第n个元素,并打印结果.
这是我的函数调用:
drop([1,2,3,4],2)
错误的输出:
[2, 4]
代替[1, 3]
然后我尝试了上面链接中的一种变体:
def drop(mylist, n):
new_list = [item for index, item in enumerate(mylist) if index % n != 0]
print(new_list)
再次,函数调用:
drop([1,2,3,4],2)
给我同样的错误结果:
[2, 4]
代替[1, 3]
如何从列表中正确删除/删除/删除第n个项目?
在您的第一个函数中,mylist[0::n]
是[1, 3]
,因为0::n
表示第一个元素为0,其他元素每第n个 元素在第一个之后.正如Daniel所建议的,您可以使用mylist[::n]
,这意味着每第n个 个元素.
在您的第二个函数索引中,索引以0开头,而0 % 0
为0,因此它不会复制第一个元素.第三个元素(2 % 2
为0)相同.所以您要做的就是new_list = [item for index, item in enumerate(mylist) if (index + 1) % n != 0]
提示:在此类功能中,您可能希望使用return
而不是print()
.
I had already looked through this post: Python: building new list from existing by dropping every n-th element, but for some reason it does not work for me:
I tried this way:
def drop(mylist, n):
del mylist[0::n]
print(mylist)
This function takes a list and n
. Then it removes every n-th element by using n-step from list and prints result.
Here is my function call:
drop([1,2,3,4],2)
Wrong output:
[2, 4]
instead of [1, 3]
Then I tried a variant from the link above:
def drop(mylist, n):
new_list = [item for index, item in enumerate(mylist) if index % n != 0]
print(new_list)
Again, function call:
drop([1,2,3,4],2)
Gives me the same wrong result:
[2, 4]
instead of [1, 3]
How to correctly remove/delete/drop every n-th item from a list?
In your first function mylist[0::n]
is [1, 3]
because 0::n
means first element is 0 and other elements are every nth element after first. As Daniel suggested you could use mylist[::n]
which means every nth element.
In your second function index is starting with 0 and 0 % 0
is 0, so it doesn't copy first element. It's same for third element (2 % 2
is 0). So all you need to do is new_list = [item for index, item in enumerate(mylist) if (index + 1) % n != 0]
Tip: you may want to use return
instead of print()
in functions like these.
这篇关于Python:如何从列表中删除/删除第n个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!