zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    web学生选课平台
    YUM仓库的搭建
    定制RPM包
    会话保持
    Nginx负载均衡器+keepalived
    LAMP搭建配置
    KVM安装搭建
    安装PHP以及搭建博客(四)伪静态
    安装PHP以及搭建博客(三)服务迁移分离
    安装PHP以及搭建博客(二)
  • 原文地址:https://www.cnblogs.com/dabiao/p/1683942.html
Copyright © 2011-2022 走看看