• Python学习笔记十一:列表(3)列表的一些方法


    (1)append方法

    说明:
        append(x)
        append方法用于在列表的尾部追加元素,参数x是插入元素的值。
    举例:

    说明:    

    append(x)    append方法用于在列表的尾部追加元素,参数x是插入元素的值。
    举例:

    1 #coding:utf-8
    2  test1 = [3,4,6,7,"Hello World"]
    3 test1.append(3.9)
    4  print test1 #reslut = [3, 4, 6, 7, 'Hello World', 3.8999999999999999]

    (2)insert方法

    说明:

        insert(index,value)

        insert方法用于在列表中插入元素。它有两个参数,index参数是索引位置,value参数是插入元素的值。

    举例:

      

    1 #coding:utf-8
    2  test1 = [3,4,6,7,"Hello World"]
    3 test1.insert(2, "insert Here")
    4  print test1 #result = [3, 4, 'insert Here', 6, 7, 'Hello World']

    (3)extend方法

    说明:
        list1.extend(list2)
        extend方法用于将两个列表合并,将list2列表的值添加到list1列表的后面。
    举例:

    1 #coding:utf-8
    2  test1 = [1,2,3,4]
    3 test2 = [5,6,7,8]
    4  print test1 #result = [1, 2, 3, 4]
    5  test1.extend(test2)
    6  print test1 #result = [1, 2, 3, 4, 5, 6, 7, 8

    (4)index方法

    说明:
        index(element)
        index方法用于取得元素element第一次出现的索引值
    举例:
    1 #coding:utf-8
    2  test1 = [1,2,3,4]
    3  print test1.index(1) #result = 0
    4  test2 = [1,1,1,1]
    5  print test2.index(1) #result = 0
    6 #如果element是一个不存在的值,就会出现错误提示
    7  print test2.index(2) #ValueError: list.index(x): x not in list
    (5)remove方法
    说明:
        remove(element)
        remove方法用于从列表中移除第一次的值。
    举例:
    1 #coding:utf-8
    2  test1 = ['One','Two','Three','Four','Five']
    3  print test1 #result = ['One', 'Two', 'Three', 'Four', 'Five']
    4  test1.remove('Two')
    5  print test1 #result = ['One', 'Three', 'Four', 'Five']
    6 #如果移除一个不存在的值,就会引发一个错误
    7  test1.remove('Six')
    8  print test1 #ValueError: list.remove(x): x not in list
    (6)pop方法
    说明:
        pop()
        pop方法用于删除列表中最后一个元素
    举例:
    1 #coding:utf-8
    2  test1 = ['One','Two','Three','Four','Five']
    3 test1.pop()
    4  print test1 #result = ['One', 'Two', 'Three', 'Four']
    5 #如果试图对一个空列表使用pop方法,则会引发一个错误!
    6  test2 = []
    7 test2.pop() #IndexError: pop from empty list
  • 相关阅读:
    替代 Hystrix,Spring Cloud Alibaba Sentinel 快速入门
    官方文档中文版!Spring Cloud Stream 快速入门
    生产环境当然要高可用,Alibaba Nacos 集群部署
    对标Eureka的AP一致性,Nacos如何实现Raft算法
    抢占云原生市场,阿里开源服务发现组件 Nacos快速入门
    使用阿里云 ECS 快速部署 WordPress 博客系统
    Spring Cloud Alibaba 实战 之 Nacos 服务注册和发现
    ASPOSE.Cells & ASPOSE.Words 操纵Excel和Word文档的 .NET Core 实例
    ASP.NET Core 3.x 中间件流程与路由体系
    以正确的方式下载和配置 ASP.NET Core 官方源码
  • 原文地址:https://www.cnblogs.com/dabiao/p/1683942.html
Copyright © 2020-2023  润新知