代码之家  ›  专栏  ›  技术社区  ›  dbr

python表达式文档中的“切片”

  •  14
  • dbr  · 技术社区  · 15 年前

    我不理解Python文档的以下部分:

    http://docs.python.org/reference/expressions.html#slicings

    这是指列表切片吗( x=[1,2,3,4]; x[0:2] )…?尤其是涉及省略号的部分。

    slice_item       ::=  expression | proper_slice | ellipsis
    

    作为表达式的切片项的转换就是该表达式。省略号切片项的转换是内置省略号对象。

    3 回复  |  直到 15 年前
        1
  •  16
  •   nosklo    15 年前

    定义简单的测试类,该类只打印正在传递的内容:

    >>> class TestGetitem(object):
    ...   def __getitem__(self, item):
    ...     print type(item), item
    ... 
    >>> t = TestGetitem()
    

    表达式示例:

    >>> t[1]
    <type 'int'> 1
    >>> t[3-2]
    <type 'int'> 1
    >>> t['test']
    <type 'str'> test
    >>> t[t]
    <class '__main__.TestGetitem'> <__main__.TestGetitem object at 0xb7e9bc4c>
    

    切片实例:

    >>> t[1:2]
    <type 'slice'> slice(1, 2, None)
    >>> t[1:'this':t]
    <type 'slice'> slice(1, 'this', <__main__.TestGetitem object at 0xb7e9bc4c>)
    

    省略号示例:

    >>> t[...]
    <type 'ellipsis'> Ellipsis
    

    带省略号和切片的元组:

    >>> t[...,1:]
    <type 'tuple'> (Ellipsis, slice(1, None, None))
    
        2
  •  21
  •   Benedikt Waldvogel assylias    11 年前

    Ellipsis 主要用于 numeric python 扩展,添加多维数组类型。因为有多个维度, slicing 变得比开始和停止索引更复杂;能够切片多个维度也是很有用的。例如,给定4x4数组,左上角区域将由切片“[:2,:2]定义。”

    >>> a
    array([[ 1,  2,  3,  4],
           [ 5,  6,  7,  8],
           [ 9, 10, 11, 12],
           [13, 14, 15, 16]])
    
    >>> a[:2,:2]  # top left
    array([[1, 2],
           [5, 6]])
    

    此处使用省略号指示未指定的其余数组维度的占位符。把它看作是表示未指定维度的完整切片[:],所以 对于3D阵列, a[...,0] 是一样的 a[:,:,0] 对于4D, a[:,:,:,0] .

    注意,实际的省略号文本(…)在python2的slice语法之外不可用,尽管有一个内置的省略号对象。这就是“省略号切片项的转换是内置省略号对象”的意思。 a[...] “是有效的糖” a[Ellipsis] “。在Python 3中, ... 表示省略号,因此可以编写:

    >>> ...
    Ellipsis
    

    如果你不使用numpy,你可以忽略所有提到的省略号。没有任何内置类型使用它,所以真正需要关心的是列表传递一个包含 start “,” stop “和” step “会员。IE:

    l[start:stop:step]   # proper_slice syntax from the docs you quote.
    

    等同于调用:

    l.__getitem__(slice(start, stop, step))
    
        3
  •  8
  •   S.Lott    15 年前

    结果就是这样。见 http://docs.python.org/reference/datamodel.html#types http://docs.python.org/library/functions.html#slice

    切片对象用于表示 当扩展切片语法为 使用。这是一片用两片 冒号,或多个切片或椭圆 用逗号分隔,例如, A[I:J:步骤]、A[I:J,K:L]或A[…, 我:J.它们也是由 内置slice()函数。

    特殊只读属性:start为 下限;停止是上限 绑定;step是步骤值;每个是 如果省略,则无。这些属性可以 有任何类型。

    x=[1,2,3,4]
    x[0:2]
    

    “0:2”转换为 Slice 对象的起始值为0,停止值为2,步骤为无。

    这个 切片 对象提供给 x __getitem__ 您定义的类的方法。

    >>> class MyClass( object ):
        def __getitem__( self, key ):
            print type(key), key
    
    
    >>> x=MyClass()
    >>> x[0:2]
    <type 'slice'> slice(0, 2, None)
    

    但是,对于内置列表类, __getslice__ 必须重写方法。

    class MyList( list ):
        def __getslice__( self, i, j=None, k=None ):
            # decode various parts of the slice values
    

    省略号是为多维切片提供的一种特殊的“忽略此维度”语法。

    也看到 http://docs.python.org/library/itertools.html#itertools.islice 更多信息。