zoukankan      html  css  js  c++  java
  • python insert()函数解析(最清晰的解释)

    欢迎关注WX公众号:【程序员管小亮】

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

    list.insert(index, obj)
    

    参数:

    • 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。

    • 4:当index < 0 且 abs(index) >= len(list)时,从头部插入obj。

    • 5:当index >= len(list)时,从尾部插入obj。

    list.insert(index = -1, obj)除外,当index = -1时,是插在倒数第二位的,也就是:

    lst = [2,2,2,2,2,2]
    lst.insert(-1,6)
    print(lst)
    
    > [2, 2, 2, 2, 2, 6, 2]
    

    例子1:

    lst = [2,2,2,2,2,2]
    lst.insert(0,0)# index=0时,从头部插入obj
    print(lst)
    
    > [0, 2, 2, 2, 2, 2, 2]
    

    例子2:

    lst = [2,2,2,2,2,2]
    lst.insert(6,7)# index > 0 且 index < len(list)时,在index的位置插入obj
    print(lst)
    
    > [2, 2, 2, 2, 2, 2, 7]
    

    例子3:

    lst = [2,2,2,2,2,2]
    lst.insert(-2,6)# 当index < 0 且 abs(index) < len(list)时,从中间插入obj
    print(lst)
    
    > [2, 2, 2, 2, 6, 2, 2]
    

    例子4:

    lst = [2,2,2,2,2,2]
    lst.insert(-20,10)# 当index < 0 且 abs(index) >= len(list)时,从头部插入obj
    print(lst)
    
    > [10, 2, 2, 2, 2, 2, 2]
    

    例子5:

    lst = [2,2,2,2,2,2]
    lst.insert(30,20)# 当index >= len(list)时,从尾部插入obj
    print(lst)
    
    > [2, 2, 2, 2, 2, 2, 20]
    

    python课程推荐。
    在这里插入图片描述

  • 相关阅读:
    sqoop安装并配置连接数据库
    Mapreduce自定义数据类型
    MapReduce入门(三)倒排索引
    复合式MapReduce之ChainJob
    android 各种xml的作用
    Android ViewPager实现软件的第一次加载的滑动效果
    Android调用系统相机和文件浏览器
    Android样式的编写格式
    Android 按钮按下效果
    Android圆角矩形的实现
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13302817.html
Copyright © 2011-2022 走看看