美文网首页
Python--序列

Python--序列

作者: VB过得VB | 来源:发表于2017-02-03 19:10 被阅读51次

    通用序列操作:索引、切片、加、乘、成员资格检查、序列长度、最大最小元素

    1、索引

    >>> greeting = 'hello
    >>> greeting[0]
    'h'
    >>> greeting[-1]
    'o'
    >>> 'hello'[1]
    'e'
    

    2、切片

    >>> numbers = [1,2,3,4,5,6,7,8,9,10]
    >>> numbers[3:6]
    [4, 5, 6]
    >>> numbers[0:1]
    [1]
    >>> numbers[-3:-1]
    [8, 9]
    >>> numbers[-3:0] # 左边索引比用变索引晚出现,结构就是空序列
    []
    >>> numbers[-3:] # 从后往前
    [8, 9, 10]
    >>> numbers[:3] # 从前往后
    [1, 2, 3]
    >>> numbers[:]
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # 复制序列
    

    2.1、步长

    >>> numbers[0:10:1]
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    >>> numbers[0:10:2]
    [1, 3, 5, 7, 9]
    >>> numbers[::4] # 取每四个元素中的第一个
    [1, 5, 9]`
    >>> numbers[8:3:-1] # 从右往左取
    [9, 8, 7, 6, 5]
    >>> numbers[10:0:-2] # 从右往左每两个取右边第一个
    [10, 8, 6, 4, 2]
    >>> numbers[0:10:-2]
    []
    >>> numbers[::-2]
    [10, 8, 6, 4, 2]
     >>>numbers[5::-2]
    [6, 4, 2]
    >>> numbers[:5:-2]
    [10, 8]
    

    开始点的元素(最左边的元素)包括在结果中,而结束点的元素(最右 边的元素)则不在切片之内。当使用一个负数作为步长时,必须让开始点(开始索引)大于结束点。在没有明确指定开始点和结束点的时候,正负数的使用可能会带来一些混淆。不过在这种情况下Python会进行正确的操作:对于一个整数步长,Python会从序列的头部开始向右提取元素;而对于负数步长,则是从序列的尾部开始向左提取元素,直到第一个元素。

    3、序列加法

    >>> [1,2,3] + [4,5,6]
    [1, 2, 3, 4, 5, 6]
    >>> 'hello' + 'world''helloworld'
    >>> [1,2,3] + 'hello'
    Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
    TypeError: can only concatenate list (not "str") to list
    

    注:两种相同类型的序列才能连接操作

    4、乘法

    >>> 'python' * 5
    'pythonpythonpythonpythonpython'
    >>> [1,2] * 10
    [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
    >>> [None] * 10
    [None, None, None, None, None, None, None, None, None, None] 
    #长度为10,无元素的列表
    

    5、成员资格检查

    >>> str = 'resfjs'
    >>> 'f' in str
    True
    >> 'w' in str
    False
    

    6、序列长度,最大最小元素

    >>> numbers = [100, 34, 678]
    >>> len(numbers)
    3
    >>> max(numbers)
    678
    >>> min(numbers)
    34
    

    相关文章

      网友评论

          本文标题:Python--序列

          本文链接:https://www.haomeiwen.com/subject/nmnrittx.html