且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从列表中删除/删除第n个元素?

更新时间:2023-02-13 20:58:13

在您的第一个函数中, mylist [0 :: n] [1、3] ,因为 0 :: n 表示第一个元素为0,其他元素在第一个之后的第n 个元素中.正如Daniel所建议的,您可以使用 mylist [:: n] ,这意味着每第n个 个元素.

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.

在第二个函数中索引从0开始,而 0%0 为0,因此它不会复制第一个元素.第三个元素相同( 2%2 为0).因此,您需要做的只是 new_list = [如果索引(1 +%)%n!= 0,则为枚举(mylist)中索引的项目,

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]

提示:在此类函数中,您可能希望使用 return 而不是 print().

Tip: you may want to use return instead of print() in functions like these.