说:
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Run Code Online (Sandbox Code Playgroud)
我知道list[::2]会删除每一个元素,所以list = [1,3,5,7,9]
如果说我需要删除每个第三个元素?所以列表将成为[1,3,7,9](5将被删除,因为它是第三个元素.我将如何继续这样做?目前,使用b = list[::3]返回[1, 7]
Mar*_*ers 10
要删除给定列表中的元素,请使用del:
del lst[::2] # delete every second element (counting from the first)
del lst[::3] # delete every third
Run Code Online (Sandbox Code Playgroud)
演示:
>>> 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]
Run Code Online (Sandbox Code Playgroud)
如果要从第二个元素中删除第二个元素,则需要为切片提供除默认值以外的起始索引:
del lst[1::2] # delete every second element, starting from the second
del lst[2::3] # delete every third element, starting from the third
Run Code Online (Sandbox Code Playgroud)
演示:
>>> 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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13472 次 |
| 最近记录: |