zoukankan      html  css  js  c++  java
  • python3--列表

    alist=[10,3.14,'hello',[200,300]]

    1、切片操作:print(alist[:1])   结果:[10]   切片出来的类型和原数据类型保持一致

    2、列表常用操作:

    #1查询:获取元素---最快是下标获取

    alist=[10,3.14,'hello',[200,300]]
    print(alist[0])
    结果:
    10

    获取下标:

    alist=[10,3.14,'hello',[200,300]]
    print(alist.index(10))
    结果:
    0

    #2修改

    alist[0]=50

    print(alist)   结果:[50,3.14,'hello',[200,300]]

    #3增加元素

    3-1:列表名:append(需要增加的元素值)---从尾部增加

    alist.append(50)

    print(alist) 结果:[10,3.14,'hello',[200,300],50]

    3-2:插入值   列表名.insert(需要的位置下标,插入的值)

    alist.insert(0,50)

    print(alist)  结果:[50,10,3.14,'hello',[200,300]]

    #4删除

    1、del---使用下标删除

    alist=[10,3.14,'hello',[200,300]]
    del alist[0],alist[1]
    print(alist)
    结果:
    [3.14, [200, 300]]
    alist=[10,3.14,'hello',[200,300]]
    del alist[1:1+2] #利用切片删除
    print(alist)
    结果:
    [10, [200, 300]]

    2、pop(下标)----有返回值

    alist=[10,3.14,'hello',[200,300]]
    print(alist.pop(0))
    print(alist)

    结果:

    10

    [3.14, 'hello', [200, 300]]

    3、remove(元素值) --每次只能删除第一个出现的值,

    alist=[10,3.14,'hello',[200,300]]
    alist.remove(3.14)
    print(alist)
    结果:
    [10, 'hello', [200, 300]]

    如果要删除多个重复元素,用while N in alist:alist.remove

    alist=[10,3.14,'hello',[200,300]]
    while 10 in alist:
        alist.remove(10)
    print(alist)
    结果:
    [3.14, 'hello', [200, 300]]

    #5合并列表

    法1:零时合并,不影响原列表

    alist=[10,3.14,'hello',[200,300]]
    print(alist+[1,2])
    print(alist)
    结果:
    [10, 3.14, 'hello', [200, 300], 1, 2]
    [10, 3.14, 'hello', [200, 300]]

    法2:扩展列表,会改变原列表

    alist=[10,3.14,'hello',[200,300]]
    alist.extend([1,2])
    print(alist)
    结果:
    [10, 3.14, 'hello', [200, 300], 1, 2]
  • 相关阅读:
    secureCRT使用pem私钥
    常用的GoLang包工具
    解决vs code 调试golang时字符串显示不全的问题
    git 常用操作
    go sqlx db.Query需手动释放
    go dlv 调试
    Ambari中superset-hive认证
    HDP3.x hive load data local inpath 设置
    dolphinscheduler-调度
    sourceTree 提交错误
  • 原文地址:https://www.cnblogs.com/guang2508/p/13127619.html
Copyright © 2011-2022 走看看