• 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']

      

  • 相关阅读:
    49. 字母异位词分组
    73. 矩阵置零
    Razor语法问题(foreach里面嵌套if)
    多线程问题
    Get json formatted string from web by sending HttpWebRequest and then deserialize it to get needed data
    How to execute tons of tasks parallelly with TPL method?
    How to sort the dictionary by the value field
    How to customize the console applicaton
    What is the difference for delete/truncate/drop
    How to call C/C++ sytle function from C# solution?
  • 原文地址:https://www.cnblogs.com/Vinson404/p/7361188.html
Copyright © 2020-2023  润新知