zoukankan      html  css  js  c++  java
  • 005 列表的基本使用

    • 简单地说,列表就是一组有顺序的数据的组合

    创建

    例1

    >>> a = []
    >>> a
    []
    >>> type(a)
    <class 'list'>
    >>> 
    >>> b = list()
    >>> b
    []
    >>> type(b)
    <class 'list'>
    >>> 
    

    例2

    >>> a = [100]
    >>> a
    [100]
    >>> type(a)
    <class 'list'>
    >>> 
    >>> b = [1, 2, 3, 4, 5]
    >>> b
    [1, 2, 3, 4, 5]
    >>> type(b)
    <class 'list'>
    >>> 
    

    常用操作

    • 访问:索引从 0 开始
    • 分片/切片:截取列表的一部分或全部,索引左闭右开

    访问

    例3

    >>> a = [0, 1, 2, 3, 4]
    >>> a[0]
    0
    >>> a[2]
    2
    >>> a[-1]
    4
    >>> a[5]
    Traceback (most recent call last):
      File "<pyshell#4>", line 1, in <module>
        a[5]
    IndexError: list index out of range
    >>> 
    

    分片

    例4

    >>> a = [0, 1, 2, 3, 4]
    >>> a[1:4]  # [1, 4)
    [1, 2, 3]
    >>> a[-4:-1]
    [1, 2, 3]
    >>> a[-1:-4]
    []
    >>> a[:]
    [0, 1, 2, 3, 4]
    >>> a[:5]  # 前 5 个
    [0, 1, 2, 3, 4]
    >>> a[3:]  # 除前 3 个
    [3, 4]
    >>> a[3:10]  # 分片时索引可以超出范围
    [3, 4]
    >>> a[-10:]
    [0, 1, 2, 3, 4]
    >>> 
    

    例5

    >>> a = list(range(10))
    >>> a
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> a[2:8:1]
    [2, 3, 4, 5, 6, 7]
    >>> a[2:8:2]
    [2, 4, 6]
    >>> 
    >>> a[2:8:0]
    Traceback (most recent call last):
      File "<pyshell#5>", line 1, in <module>
        a[2:8:0]
    ValueError: slice step cannot be zero
    >>> 
    

    例6

    >>> a = list(range(10))
    >>> a
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> a[6:2:-1]
    [6, 5, 4, 3]
    >>> a[-1:-5:-1]
    [9, 8, 7, 6]
    >>> 
    

    id()

    • id(): 显示一个变量或者数据的”身份证“

    例7

    >>> a = 100
    >>> b = 200
    >>> id(a)
    140709107680128
    >>> id(b)
    140709107683328
    >>> 
    

    例8

    >>> a = 100
    >>> b = a
    >>> id(a)
    140709107680128
    >>> id(b)
    140709107680128
    >>> 
    

    例9

    >>> a = [1, 2, 3, 4, 5]
    >>> b = a  # 合用一份数据
    >>> c = a[:]  # 新生成一份数据
    >>> id(a)
    2186608330432
    >>> id(b)
    2186608330432
    >>> id(c)
    2186608329792
    >>> 
    >>> a[0] = 100
    >>> a
    [100, 2, 3, 4, 5]
    >>> b
    [100, 2, 3, 4, 5]
    >>> c
    [1, 2, 3, 4, 5]
    >>> 
    
  • 相关阅读:
    在PHP语言中使用JSON
    PHP中生成json信息的方法
    Oracle 11g数据库详细安装步骤图解
    spring data jpa
    missing artifact com.oracle:ojdbc14:jar:10.2.0.2.0解决办法
    HDU 2841 Visible Trees
    LightOJ 1348 Aladdin and the Return Journey
    FZU 2082 过路费
    BZOJ 1036: [ZJOI2008]树的统计Count
    BZOJ 2243: [SDOI2011]染色
  • 原文地址:https://www.cnblogs.com/yorkyu/p/10248899.html
Copyright © 2011-2022 走看看