zoukankan      html  css  js  c++  java
  • Python 列表

    工厂函数list 创建列表。

    更新列表:

    >>>list = ['physics', 'chemistry', 1997, 2000]
    >>>list[2] = 2001
    >>>list
    ['physics', 'chemistry', 2001, 2000]

    删除列表元素:

    >>>list1 = ['physics', 'chemistry', 1997, 2000]
    >>>del list1[2]
    >>>list1
    ['physics', 'chemistry', 2000]

    列表常用函数:

    函    数 说    明
    list.append(obj)
    用于在列表末尾添加新的对象。(不返回,直接修改原来列表)
    list.count(obj)
    返回某个元素在列表中出现的次数。
    list.extend(seq)
    在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)。(不返回,直接修改原来列表)
    list.index(obj)
    返回从列表中找出某个值第一个匹配项的索引位置。(没有找到对象则抛出异常。)
    list.insert(index, obj)
    将指定对象插入列表的指定位置。(无返回值)
    list.pop(index=list[-1])
    移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。(返回从列表中移除的元素对象。)
    list.remove(obj)
    移除列表中某个值的第一个匹配项。(无返回值)
    list.reverse()
    反向列表中元素。(无返回值)
    list.sort([func])
    对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数。(无返回值)

    append()与extend(): append() 方法向列表的尾部添加一个新的元素。extend()方法只接受一个列表作为参数,并将该参数的每个元素都添加到原有的列表中。

    def changeextend(str):
        "print string with extend"
        mylist.extend([40,50,60]);
        print "print string mylist:",mylist
        return
    def changeappend(str):
        "print string with append"
        mylist.append( [7,8,9] )
        print "print string mylist:",mylist
        return
    mylist = [10,20,30]
    changeextend( mylist );
    print "print extend mylist:", mylist
    changeappend( mylist );
    print "print append mylist:", mylist

    输出:

    print string mylist: [10, 20, 30, 40, 50, 60]
    print extend mylist: [10, 20, 30, 40, 50, 60]
    print string mylist: [10, 20, 30, 40, 50, 60, [7, 8, 9]]
    print append mylist: [10, 20, 30, 40, 50, 60, [7, 8, 9]]

    list.pop(index=list[-1]):

    >>>aList = [123, 'xyz', 'zara', 'abc']
    >>>print "A List : ", aList.pop()
    A List :  abc
    >>>print "B List : ", aList.pop(2)
    B List :  zara
    >>>aList
    [123,'xyz']

      

  • 相关阅读:
    启动mysql时显示:/tmp/mysql.sock 不存在的解决方法
    python在使用MySQLdb模块时报Can't extract file(s) to egg cacheThe following error occurred while trying to extract file(s) to the Python eggcache的错误。
    文档发布测试
    我的日常
    CSS-基础优化策略
    Git-基本操作
    Git-配置SSH公钥
    Git-免密提交
    Wx-mpvue开发小程序
    Vue-移动端开发全家桶
  • 原文地址:https://www.cnblogs.com/Vinson404/p/7361188.html
Copyright © 2011-2022 走看看