在Python中反转切片 [英] Invert slice in python
问题描述
有没有简单的方法可以在python中反转列表切片?给我一切除了一片吗?例如:
Is there any simple way to invert a list slice in python? Give me everything except a slice? For example:
给出列表a = [0,1,2,3,4,5,6,7,8,9]
,我希望能够提取[7,8,9,0,1,2]
,即除[3:7]以外的所有内容.
Given the list a = [0,1,2,3,4,5,6,7,8,9]
I want to be able to extract [7,8,9,0,1,2]
i.e. everything but a[3:7].
从逻辑上考虑,我认为a [-3:3]会给我我想要的东西,但它只会返回一个空列表.
Thinking about it logically, I thought that a[-3:3] would give me what I want, but it only returns an empty list.
我更喜欢一个适用于python 2和3的解决方案
I am preferring a solution which will work for both python 2 and 3
推荐答案
如果您愿意销毁清单(或清单的副本),则可以剪掉不需要的部分:
If you're willing to destroy the list (or a copy of it) you can cut out the part you don't want:
>>> a = [0,1,2,3,4,5,6,7,8,9]
>>> a[3:7] = []
>>> a
[0, 1, 2, 7, 8, 9]
订购顺序与您要求的顺序不同,尽管这对您可能并不重要.
The order is not the same as what you asked for, though that might not be important to you.
这篇关于在Python中反转切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!