如何用切片符号 a[::-1] 解释序列的反转 [英] How to explain the reverse of a sequence by slice notation a[::-1]

查看:60
本文介绍了如何用切片符号 a[::-1] 解释序列的反转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 python.org 教程

<块引用>

切片索引有有用的默认值;省略的第一个索引默认为零,省略的第二个索引默认为被切片的字符串的大小.

<预><代码>>>>a = "你好">>>打印(a[::-1])奥列

正如教程所说 a[::-1] 应该等于 a[0:5:-1]

但是 a[0:5:-1] 为空如下:

<预><代码>>>>打印(len(a[0:5:-1]))0

问题不是 explain-slice-notation 的副本.这个问题是关于python中切片的一般用法.

解决方案

我认为文档在这方面可能有点误导,但是切片的可选参数(如果省略)与使用 None 相同:

<预><代码>>>>a = "你好">>>[::-1]'olleh'>>>[无:无:-1]'olleh'

您可以从 CPython 字节码中看到以上 2 个切片是相同的:

<预><代码>>>>导入文件>>>dis.dis('a[::-1]') # 或 dis.dis('a[None:None:-1]')1 0 LOAD_NAME 0 (a)3 LOAD_CONST 0(无)6 LOAD_CONST 0(无)9 LOAD_CONST 2 (-1)12 BUILD_SLICE 315 BINARY_SUBSCR16 RETURN_VALUE

对于负 stepNone 的替代值为 len(a) - 1 用于 start> 和 -len(a) - 1 用于 end:

<预><代码>>>>a[len(a)-1:-len(a)-1:-1]'olleh'>>>[4:-6:-1]'olleh'>>>a[-1:-6:-1]'olleh'

这可能有助于您将其形象化:

 he l l o0 1 2 3 4 5-6 -5 -4 -3 -2 -1

From the python.org tutorial

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

>>> a = "hello"
>>> print(a[::-1])
olleh

As the tutorial says a[::-1] should equals to a[0:5:-1]

but a[0:5:-1] is empty as follows:

>>> print(len(a[0:5:-1]))
0

The question is not a duplicate of explain-slice-notation. That question is about the general use of slicing in python.

解决方案

I think the docs are perhaps a little misleading on this, but the optional arguments of slicing if omitted are the same as using None:

>>> a = "hello"
>>> a[::-1]
'olleh'
>>> a[None:None:-1]
'olleh'

You can see that these 2 above slices are identical from the CPython bytecode:

>>> import dis
>>> dis.dis('a[::-1]') # or dis.dis('a[None:None:-1]')
  1           0 LOAD_NAME                0 (a)
              3 LOAD_CONST               0 (None)
              6 LOAD_CONST               0 (None)
              9 LOAD_CONST               2 (-1)
             12 BUILD_SLICE              3
             15 BINARY_SUBSCR
             16 RETURN_VALUE

For a negative step, the substituted values for None are len(a) - 1 for the start and -len(a) - 1 for the end:

>>> a[len(a)-1:-len(a)-1:-1]
'olleh'
>>> a[4:-6:-1]
'olleh'
>>> a[-1:-6:-1]
'olleh'

This may help you visualize it:

    h  e  l  l  o   
    0  1  2  3  4  5
-6 -5 -4 -3 -2 -1

这篇关于如何用切片符号 a[::-1] 解释序列的反转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆