[问题] 想问string 有关slice反转 [::-1]的问题

楼主: nicehorse06 (嘿嘿马)   2015-07-22 23:29:04
我想问有关反转str的问题
str="play"
print str[::-1] #yalp
print str[0:len(str):-1] #none
print str[len(str):0:-1] #yal
print str[len(str)::-1] #yalp
print str[-1:-5:-1] #yalp
如果step为正[::1],start默认为0而end默认为len(str)
我不知道为负[::-1]的第一个空白start和第二个空白end会带入什么
一开始以为会等于这个str[0:len(str):-1],但不是
我想请问step为负的时候,前面两个默认是什么
我爬了一下 相关的文章是
https://www.ptt.cc/bbs/Python/M.1291617432.A.045.html
作者: LiloHuang (十年一刻)   2015-07-22 23:50:00
默认值都是 None,可试试 str[None:None:-1]
楼主: nicehorse06 (嘿嘿马)   2015-07-22 23:54:00
str[None:None:-1] 可以耶 那填None要怎么想?
作者: LiloHuang (十年一刻)   2015-07-22 23:58:00
这简单,看 Python 原始码便知,http://goo.gl/mL1928在 PySlice_GetIndicesEx(...) 里面有一段逻辑基本上就是如果 step = -1,则 defstart = length - 1defstop = -1,因此会产生新的 list 装载相反的顺序当然这个情况是在 start 跟 stop 都是 Py_None 的时候才会使用 defstart 跟 defstop,看看原始码你就懂了 :)
楼主: nicehorse06 (嘿嘿马)   2015-07-23 08:45:00
谢谢你,原来问题在原始码所以Python就是ㄧ个用C语言来写的程式囉?因此网络上说完美结合了C
作者: LiloHuang (十年一刻)   2015-07-23 09:03:00
Python 有很多实作的版本,我猜测你是使用 CPython像是 IronPython 跟 PyPy 就是不同的 interpreter 实作其实这个问题官方文件有详载 https://goo.gl/Tr13oP坦白说文件我花了好一回才找到 XD 看实作原始码比较快
楼主: nicehorse06 (嘿嘿马)   2015-07-23 09:27:00
我学的还很浅分不清楚版本,真的谢谢你用心的回答!

Links booklink

Contact Us: admin [ a t ] ucptt.com