gpt4 book ai didi

python - 如何首先删除列表中的每个第二个元素,然后删除剩余的每个元素?

转载 作者:太空狗 更新时间:2023-10-29 22:16:04 26 4
gpt4 key购买 nike

说:

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

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

最佳答案

要从给定列表中删除元素,请使用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]

关于python - 如何首先删除列表中的每个第二个元素,然后删除剩余的每个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22023107/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com