python删除列表第几个元素,Python:如何从列表中删除/删除第n个元素?

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值