所以我真的没有在切片中得到stride参数的处理.
例如,"123456"[::-2]生产"642",但为什么"123456"[1::-2]生产"2"和"123456"[2::-2]生产"31"?
g.d*_*d.c 24
最简单的解释方法可能是解决您的示例:
"123456"[::-2]
# This takes the whole string ([::])
# Then it works backward (-)
# and it does every other character (2)
"123456"[1::-2]
# This is also working backward (-)
# every other character (2)
# but starting at position 1, which is the number 2.
"123456"[2::-2]
# Again, working backward (-)
# Every other character (2)
# begin at position 2, so you end up with positions 2, and 0, or '31'
Run Code Online (Sandbox Code Playgroud)
切片语法是[<start>:<end>:step].如果<start>省略并且步骤为负,则从字符串的结尾开始.
那是因为语法是 string[start:end:step]
"123456"[::-2]
Run Code Online (Sandbox Code Playgroud)
产生“ 642”,因为它将从最后一个字符开始。这是因为您没有提供从哪个位置执行切片。因此它将从最后一个返回2个字符,直到到达第一个。
"123456"[1::-2]
Run Code Online (Sandbox Code Playgroud)
产生“ 2”是因为您告诉Python从第二个字符开始(字符串的索引1),并且告诉Python从该位置返回2个步骤。在这种情况下,Python显然只会返回“ 2”。这是因为,当Python尝试返回2步时,它仅一步就已经命中了字符串中的第一个字符。
"123456"[2::-2]
Run Code Online (Sandbox Code Playgroud)
您应该现在就可以弄清楚这一点。但是我还是要解释一下。因此,您告诉Python从第三个字符(或索引2)开始,然后从那里返回2步,直到到达第一个字符。因此,它将从“ 3”开始,然后返回2步,并且意外地到达了第一个字符-恰好是“ 1”。因此Python会给您“ 31”
请记住,指数从零开始.考虑到这一点,如果将字符串更改为'012345'以下内容可能会更清楚:
In [1]: '012345'[1::-2]
Out[1]: '1'
In [2]: '012345'[2::-2]
Out[2]: '20'
In [3]: '012345'[5::-2]
Out[3]: '531'
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,切片确实从正确的索引开始,并且在每一步都采取正确的(负)步幅,直到到达字符串的开头.
| 归档时间: |
|
| 查看次数: |
17703 次 |
| 最近记录: |