a[-1:-2:-1]这个什么意思

a[-1:-2:-1]这个什么意思

RT
a=[2,3,1]
print a[-1:-2:-1]
上列结果为什么会是 1 的呢?
各位高手 在线等答案
a[-1:-2:-1]   # [-1:-2] 最後一個到尾2 (尾2不計), 最後一個 -1 就是從後面開始.....

[Copy to clipboard] [ - ]
CODE:
>>a = [3,2,1]
>>print a[::-1]
[1,2,3]
>>print a[::-2]
[1,3]

没看明白,是前两个切片定义了开始地址?
(A:B):C这样理解?


QUOTE:
原帖由 edwardhey 于 2008-4-2 23:34 发表
RT
a=[2,3,1]
print a[-1:-2:-1]上列结果为什么会是 1 的呢?

a[-1:-2:-1] 中index为负数时,从list末尾向前看
a[-1:-2]是取a的最后两位的slice,设b=a[-1:-2] ,   b = [3,1]
b[-1] 就是[3,1]的最后一个元素,也就是1


[Copy to clipboard] [ - ]
CODE:
a = [2,3,1]
a[-1:-2]是取a的最后两位的slice,设b=a[-1:-2] ,   b = [3,1]

# this one is incorrect....
# b = a[-1:-2] , b will never include the second element from the last
# so b is [1], not [3,1]

a[::-1]   #just remember [::-1] is equal to reverse() function


QUOTE:
原帖由 eookoo 于 2008-4-4 12:46 发表

a = [2,3,1]
a[-1:-2]是取a的最后两位的slice,设b=a[-1:-2] ,   b = [3,1]

# this one is incorrect....
# b = a[-1:-2] , b will never include the second element from the last
# so b is [1], no ...

是的,eookoo是正确的,thanks
我说错了,太想当然,没有去确认>_< 以后会注意的

s[i:j:k]  是slice of s from i to j with step k   (而不是按照i,j,k 依次执行slice)
所以, 通过 b=[-1:-2] ,b[-1]这个顺序计算的想法,是完全不成立的

不过,eookoo提到b=a[-1:-2] 得到[1] , 似乎也不对,如果计算b=a[-1:-2] is [] ,如果计算a[-1:-2:-1],应该不用计算 b=a[-1:-2]这个临时值
也可能我哪里理解有偏差  讨论一下,挺有意思的