如何首先删除列表中的每个第二个元素,然后每三个元素还剩下什么?

时间:2014-02-25 18:33:22

标签: python list

说:

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

我知道list[::2]会删除每一个元素,所以list = [1,3,5,7,9] 如果说我需要删除每个第三个元素怎么办?因此列表将变为[1,3,7,9](因为它是第三个元素,所以将被删除。我将如何继续这样做? 目前,使用b = list[::3]会返回[1, 7]

4 个答案:

答案 0 :(得分:9)

要从给定列表删除元素,请使用del

del lst[::2]  # delete every second element (counting from the first)
del lst[::3]  # delete every third

演示:

>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> del lst[::2]
>>> lst
[2, 4, 6, 8, 10]
>>> del lst[::3]
>>> lst
[4, 6, 10]

如果要从第二个元素中删除第二个元素,则需要为切片指定一个非默认值的起始索引:

del lst[1::2]  # delete every second element, starting from the second
del lst[2::3]  # delete every third element, starting from the third

演示:

>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> del lst[1::2]
>>> lst
[1, 3, 5, 7, 9]
>>> del lst[2::3]
>>> lst
[1, 3, 7, 9]

答案 1 :(得分:1)

您的初始语句会保存其不会删除的所有其他值。你也不应该把你的变量变成“列表”。

给出上面显示的原始值

del mylist[::2]

将返回列表的偶数值

del mylist[1::2]

将根据您的要求返回奇数值。遵循标准

del mylist[::3] 

将删除列表中的第三个值。

答案 2 :(得分:1)

对于令人难以置信的长单行:

>>> [el for i,el in enumerate([el for i,el in enumerate([1,2,3,4,5,6,7,8,9,10]) if (i+1)%2]) if (i+1)%3]
[1,3,7,9]

以上的伪代码:

for (index, value) in [1,2,3,4,5,6,7,8,9,10]:
    if index+1 is divisible by 2: toss it
    else: add it to new_list

for (index, value) in new_list:
    if index+1 is divisible by 3: toss it
    else: add it to final_list

print(final_list)

答案 3 :(得分:0)

def remove_nums(int_list):
    #list starts with 0 index
    position = 3 - 1 
    idx = 0
    len_list = (len(int_list))
    
    while len_list>0:
        idx = (position+idx)%len_list
        print(int_list.pop(idx))
        len_list -= 1
    nums = [1,2,3,4,5,6,7,8,9,10]
    remove_nums(nums)