[英]Slicing to reverse part of a list in python
I have a list, of which I want to extract a subslice from back to end. 我有一个列表,我想从后到尾提取一个子列表。 With two lines of code, this is
有两行代码,这是
mylist = [...]
mysublist = mylist[begin:end]
mysublist = mysublist[::-1]
Is there a slicing notation to get the same effect in one line? 是否有切片符号在一行中获得相同的效果? This
这个
mysublist = mylist[end:begin:-1]
is incorrect, because it includes the end
and excludes the begin
elements. 是不正确的,因为它包含
end
并排除了begin
元素。 This 这个
mysublist = mylist[end-1:begin-1:-1]
fails when begin
is 0, because begin-1
is now -1
which is interpreted as the index of the last element of mylist
. 当
begin
为0时失败,因为begin-1
现在是-1
,它被解释为mylist
的最后一个元素的索引。
Use None
if begin
is 0
: 如果
begin
为0
请使用None
:
mysublist = mylist[end - 1:None if not begin else begin - 1:-1]
None
means 'default', the same thing as omitting a value. None
意味着'默认',与省略值相同。
You can always put the conditional expression on a separate line: 您始终可以将条件表达式放在单独的行中:
start, stop, step = end - 1, None if not begin else begin - 1, -1
mysublist = mylist[start:stop:step]
Demo: 演示:
>>> mylist = ['foo', 'bar', 'baz', 'eggs']
>>> begin, end = 1, 3
>>> mylist[end - 1:None if not begin else begin - 1:-1]
['baz', 'bar']
>>> begin, end = 0, 3
>>> mylist[end - 1:None if not begin else begin - 1:-1]
['baz', 'bar', 'foo']
您可以简单地将两行折叠成一行:
mysublist = mylist[begin:end][::-1]
您始终可以使用功能转换的强大功能:
mysublist = list(reversed(mylist[begin:end]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.