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]
  • 相关阅读:
    js如何判断访问来源是来自搜索引擎(蜘蛛人)还是直接访问
    thinkphp AOP(面向切面编程)
    crontab命令详解 含启动/重启/停止
    直播协议的选择:RTMP vs. HLS
    说一下PHP中die()和exit()区别
    宝塔Linux常用命令
    阿里云Redis公网连接的解决办法
    DMA及cache一致性的学习心得 --dma_alloc_writecombine【转】
    DMA内存申请--dma_alloc_coherent 及 寄存器与内存【转】
    内核中container_of宏的详细分析【转】
  • 原文地址:https://www.cnblogs.com/guang2508/p/13127619.html
Copyright © 2011-2022 走看看