Python: how to remove/delete every n-th element from list?

╄→尐↘猪︶ㄣ 提交于 2020-01-11 09:15:56

问题


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?


回答1:


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.




回答2:


Let's say you have the list :

a = [1,2,3,4,5,6,7,8,9,10]

If you want every k-th element you can do something like

del a[k-1::k]

Example with k=3

The current list is now [1, 2, 4, 5, 7, 8, 10]




回答3:


The output is correct, you are removing the the elements with index 0, n, 2n, ... . So 1 and 3 are removed, 2 and 4 are left. So if you want to print the 0, n, 2n, ... element, just write

print(mylist[::n])



回答4:


your first approach looks good to me - you just have to adapt your start index if you want to drop the elements 1, 1+n, 1+2n, ... (as seems to be the case):

lst = list(range(1, 5))
del lst[1::2]
print(lst)



回答5:


Another way to do this, would be to generate a new list containing only the elements you need.

newList = [x for i, x in enumerate(myList) if i%n !=0]

If n were 5, this would return a list containing the elements [1,2,3,4,6,7,8,9,11...] The advantage of doing it this way is that you keep your original list which is useful if you're going to reuse the data. However, if you're worried about saving memory, then probably not the best.



来源:https://stackoverflow.com/questions/32925532/python-how-to-remove-delete-every-n-th-element-from-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!