Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
634 views
in Technique[技术] by (71.8m points)

python - How to remove/delete every n-th element from list?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Let's say you have the list:

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

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

del a[k-1::k]

For example with k = 3, the current list is now

[1, 2, 4, 5, 7, 8, 10]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...