• Python List insert()方法详解


    1.功能
    insert()函数用于将指定对象插入列表的指定位置。

    2.语法
    list.insert(index, obj)

    3.参数
    index: 对象obj需要插入的索引位置。
    obj: 插入列表中的对象。

    共有如下5种场景:
    场景1:index=0时,从头部插入obj
    场景2:index > 0 且 index < len(list)时,在index的位置插入obj
    场景3:当index < 0 且 abs(index) < len(list)时,从中间插入obj,如: -1 表示从倒数第1位插入obj; -2 表示从倒数第1位插入obj
    场景4:当index < 0 且 abs(index) >= len(list)时,从头部插入obj
    场景5:当index >= len(list)时,从尾部插入obj

    4.返回值
    该方法没有返回值,但会在列表指定位置插入对象。

    5.实例

    >>> lst = [1,2,3,4,5] #创建一个列表
    >>> lst.insert(0,0) #从列表第1个位置,插入元素0 --场景1 
    >>> lst
    [0, 1, 2, 3, 4, 5]
    >>> lst.insert(6,7) #从列表第6个位置,插入元素7 --场景2 
    >>> lst
    [0, 1, 2, 3, 4, 5, 7]
    >>> lst.insert(-1,6) #从列表第-1个位置,插入元素6 --场景3 
    >>> lst
    [0, 1, 2, 3, 4, 5, 6, 7]
    
    >>> lst.insert(-20,10) #从列表第-20个位置,插入元素10 --场景4 
    >>> lst
    [10, 0, 1, 2, 3, 4, 5, 6, 7]
    
    >>> lst.insert(30,20) #从列表第30个位置,插入元素20 --场景5 
    >>> lst
    [10, 0, 1, 2, 3, 4, 5, 6, 7, 20]
  • 相关阅读:
    css display和vertical-align 属性
    Python:time模块/random模块/os模块/sys模块
    css display和vertical-align 属性
    初始面向对象
    模块小记
    迭代器与生成器
    默认参数的陷阱自我心得
    初始函数
    文件操作
    python基础知识补充
  • 原文地址:https://www.cnblogs.com/huangbiquan/p/7863056.html
Copyright © 2020-2023  润新知