Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么s[0:4:-1]在Python中不返回任何内容?_Python_Python 3.x_Memory_Slice - Fatal编程技术网

为什么s[0:4:-1]在Python中不返回任何内容?

为什么s[0:4:-1]在Python中不返回任何内容?,python,python-3.x,memory,slice,Python,Python 3.x,Memory,Slice,当s='abcdefg',s[0:4:-1]和s[1:-1:-1]在Python3中不返回任何内容。但是,s[:4:-1]返回“gf”。有人能解释这两种情况背后的机制吗(特别是在内存方面)?开始总是迭代的第一个索引 停止是迭代的结束边界 步骤为迭代提供方向和步长。因此迭代总是从开始到停止,方向是步骤的符号 因此,s[start:stop:step]意味着获取字符s[start],s[start+step],s[start+2*step],…,等等,直到到达stop 换句话说,s[start:st

s='abcdefg'
s[0:4:-1]
s[1:-1:-1]
在Python3中不返回任何内容。但是,
s[:4:-1]
返回
“gf”
。有人能解释这两种情况背后的机制吗(特别是在内存方面)?

开始总是迭代的第一个索引

停止
是迭代的结束边界

步骤
为迭代提供方向和步长。因此迭代总是从
开始
停止
,方向是
步骤
的符号

因此,
s[start:stop:step]
意味着获取字符
s[start]
s[start+step]
s[start+2*step]
,…,等等,直到到达
stop

换句话说,
s[start:stop:-1]
并不等同于
reversed(s[start:stop])

例子 因此,在您的示例
s[0:4:-1]
中,步骤
为负值,因此迭代过程立即停止,因为
start
索引已经位于
stop的左侧。

a b c d e f g h
0 1 2 3 4 5 6 7
^       ^
s       s
t       t
a       o
r       p
t

<-------- orientation
最后,将
start
留空表示从字符串末尾开始。这就是为什么您会看到从末尾到索引
4
的所有字符都是反向的

a b c d e f g h
0 1 2 3 4 5 6 7
        ^     ^
        s     s
        t     t
        o     a
        p     r
              t

<-------- orientation
a b c d e f g h
0 1 2 3 4 5 6 7
^     ^
s s
t t
奥阿
PR
T

你可能想准备好《我的世界》的这个可能的副本,因为它没有特别利用OP的cornercaseHi@OlivierMelançon,所以它不是一个完美的副本,我已经读过这篇文章了,我认为我的问题没有答案。Geek先生,如上所述,线程无法回答为什么s[0:4:-1]不返回任何内容,因此我不认为我的问题是重复的。@SidLin它实际上是重复的,但非常简短。请参阅我的答案以获得完整的解释注意,除了规范的反向切片(
[::-1]
)之外,通常更难解释反向运行的切片,因此即使它的效率稍低,通常最好将切片作为正向切片执行,然后将其反向,例如
x[:4][:-1]
而不是更快,但更难阅读的等价物,
x[3::-1]
@ShadowRanger实际上,我同意可读性问题。我甚至想补充一点,当迭代器足够时,我通常更喜欢可读性更强的
反转(x[:4])
a b c d e f g h
0 1 2 3 4 5 6 7
        ^     ^
        s     s
        t     t
        o     a
        p     r
              t

<-------- orientation