关于阵列:Python的倒列表

Python: Reversing lists

本问题已经有最佳答案,请猛点这里访问。

好吧,我已经搜索了多个线程,并在倒排列表(比如这个和这个)上遇到了有用的讨论;我从这些列表中得到的是使用

1
2
S = ("hello")
print(S[::-1])

1
2
S = ("hello")
print(S[len(S):-len(S)-1:-1])

但我不明白背后的逻辑!假设我想用

1
2
S = ("hello")
print(S[len(S):0:-1])

我会得到"olle"而不是"olleh",因为0或"h"是"end",而python会停在那里;所以我的直觉是通过0,也就是-1,所以它会停在-1,也包括0:

1
2
S = ("hello")
print(S[len(S):-1:-1])

但突然间Python什么也没回?!是因为python认为它是len(s)-1吗?哦,我的上帝。。那么S[::-1]之间的"is"是什么使它起作用的呢?S[len(s):-len(s)-1:-1]是如何理解的?-5-1?等于-6…所以

1
2
S = ("hello")
S[6:-6:-1]

作品。。。这意味着python将包括6、5、4、3、2、1、0、-1、-3、-4、-5??


1
s[start: stop : step]

当阶跃值为负值时:

Here both 6 and -6 are actually out of index for s, as s is just 5
character long. So the start value is picked as min(6,len(s)-1) in
this case, and stop value (-6) as also out of index so it can can be
skipped completely and python uses None as a value for it.

1
2
3
4
5
6
7
8
9
>>> s ="HELLO"
>>> s[6:-6:-1]
'OLLEH'
>>> s[ min(6,len(s)-1) : -6 :-1]
'OLLEH'
>>> s[ min(6,len(s)-1) : None :-1] #None also works fine
'OLLEH'
>>> s[6:-6:-1]
'OLLEH'

Now if the string has more than 6 characters:

1
2
3
4
5
6
7
8
>>> s ="HELLO, World"
#now you can't set the stop value as `None` as -6 is a valid index for this string.
>>> s[ min(9,len(s)-1) : -6 :-1]
'roW'
>>> s[ min(9,len(s)-1) : None :-1]  #can't use None this time
'roW ,OLLEH'
>>> s[9:-6:-1]
'roW'