• python(索引/切片)


    一.索引

    1.索引值从左到右-->从0开始,索引值从右到左-->从-1开始

    • 取值格式var[index]
    >>> name = "xinfangshuo"
    >>>
    >>> name[0]
    'x'
    >>> name[5]
    'n'
    >>> name[-1]
    'o'
    >>> name[-2]
    'u'

    2.注意:整型int和字典dict和集合set不支持索引取值

    >>> age = 123
    >>>
    >>> age[1]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'int' object has no attribute '__getitem__'
    >>> age = "123"
    >>> age[1]
    '2'
    >>> name = {"name1":"zhangsan","name2":"lisi","name3":"wangwu"}
    >>>
    >>> name[1]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 1
    >>>
    >>> set = {"zhangsan","lisi","wangwu"}
    >>>
    >>> set[1]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'set' object does not support indexing

    3.多维数组/列表,索引取值

    """多维数组,索引取值"""
    >>> name = ("zhangsan","lisi","wangwu","zhaoliu","wangba",("zhengying","lizhipeng","lvlinlin"))
    >>>
    >>> name[5][1]
    'lizhipeng'
    >>>
    >>> list = [1,2,3,4,[5,6,7,[8,9,0]]]
    >>>
    >>> list[4][3][1]
    9
    >>> list[-1][-1][-2]
    9

    二.切片  var[start_index:end_index]

    • 注意:切出的值不包含end_index的值

    1.正切

    >>> name = "xinfangshuo"
    >>>
    >>> name[3:6]
    'fan'
    >>> name[3:7]
    'fang'
    >>> name[0:11]
    'xinfangshuo'
    >>> name[0:]
    'xinfangshuo'
    >>> name[:]
    'xinfangshuo'

    2.反切

    >>> name = "xinfangshuo"
    >>> 
    >>> name[:-1]
    'xinfangshu'
    >>> name[:-2]
    'xinfangsh'
    >>> name[3:-4]
    'fang'

    3.跳级切

    >>> name = "xinfangshuo"
    >>>
    >>> name[3:7]
    'fang'
    >>> name[3:7:]
    'fang'
    >>> name[3:7:1]
    'fang'
    >>> name[3:7:2]
    'fn'
    >>> name[7:3:2]
    ''
    >>> name[::3]
    'xfgu'

    4.反跳级切

    • 从右往左切
    • start_index位置要在end_index位置的右边
    >>> name = "xinfangshuo"
    >>>
    >>> name[-1:-8:-2]
    'ohga'
    >>> name[-1:8:-2]
    'o'
    >>>
    >>> name[1:10:-2]
    ''
    >>> name[10:1:2]
    ''
    >>> name[10:1:-2]
    'ohgan'
  • 相关阅读:
    .net 操作XML小结
    Oracle 10g RAC的负载均衡配置
    数据仓库建模与ETL实践技巧
    Red Hat Linux的分区
    用C#实现MVC(Model View Control)模式介绍
    SQL SERVER 日期函数大全
    ORACLE RAC工作原理
    NVARCHAR ,VARCHAR,NCHAR,CHAR区别
    SQLserver中用convert函数转换日期格式
    Linux之远程登录和文件传输
  • 原文地址:https://www.cnblogs.com/ZhengYing0813/p/11718154.html
Copyright © 2020-2023  润新知