是否有语法来获取不在给定切片内的列表元素?鉴于切片 [1:4] 很容易获得这些元素:
>>> l = [1,2,3,4,5]
>>> l[1:4]
[2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
如果我想要列表的其余部分,我可以这样做:
>>> l[:1] + l[4:]
[1, 5]
Run Code Online (Sandbox Code Playgroud)
有没有更简洁的方法来做到这一点?我意识到我可能太需要了,因为这已经非常简洁了。
编辑:我不认为这是python中Invert slice的重复,因为我不想修改我的原始列表。
小智 3
If you want to modify the list in-place, you can delete the slice:
>>> l = [1, 2, 3, 4, 5]
>>> del l[1:4]
>>> l
[1, 5]
Run Code Online (Sandbox Code Playgroud)
Otherwise your originally suggestion would be the most succinct way. There isn't a way to get the opposite of a list slice using a single slice statement.
| 归档时间: |
|
| 查看次数: |
1807 次 |
| 最近记录: |