Python list方法總結

1.用於在列表末尾添加新的元素(對象)

    L.append(object) -- append object to end

       >>>l = ['sam','shaw','stiven']

       >>>l

       ['sam','shaw', 'stiven']

       >>>l.append('alice')

       >>>l

       ['sam','shaw', 'stiven', 'alice']

2.用於統計某個元素在列表中出現的次數。

    L.count(value) -> integer -- returnnumber of occurrences of value

       >>>l = ['sam','amy','miya','sam']

       >>>l

       ['sam','amy', 'miya', 'sam']

       >>>l.count('sam')

       2

       >>>l.count('amy')

       1

3.用於在列表末尾一次性追加另一個序列中的多個值(用新列表擴展原來的列表)

    L.extend(iterable) -- extend list byappending elements from the iterable

       >>>l = ['sam','amy']

       >>>y = [123,'boy']

       >>>l.extend(y)

       >>>l

       ['sam','amy', 123, 'boy']

4.用於從列表中找出某個值第一個匹配項的索引位置

    L.index(value, [start, [stop]]) ->integer -- return first index of value

    Raises ValueError ifthe value is not present.

        >>> l = ['sam','amy','miya']

        >>> l.index('amy')

        1

5.用於將指定對象插入列表

    L.insert(index, object) -- insert object beforeindex

    index -- 對象object需要插入的索引位置

    object -- 要出入列表中的對象

       >>>l = ['sam','amy','miya']

       >>>l.insert(2,'koko')

       >>>l

       ['sam','amy', 'koko', 'miya']

6.用於移除列表中的一個元素(默認最後一個元素),並且返回該元素的值

    L.pop([index]) -> item -- remove andreturn item at index (default last).

 Raises IndexError if list isempty or index is out of range.

       >>>l = ['sam','amy','miya','sam']

       >>>l.pop()

       'sam'

       >>>l

       ['sam','amy', 'miya']

       >>>l.pop(1)

       'amy'

       >>>l

       ['sam','miya']

7.用於移除列表中某個值的第一個匹配項

    L.remove(value) -- remove first occurrenceof value.

    Raises ValueError ifthe value is not present.

        >>> l = [123, 'xyz', 'zara', 'abc','xyz']

        >>> l.remove('xyz')

       >>>l

       [123,'zara', 'abc', 'xyz']

       >>>l.remove('shaw')

       Traceback(most recent call last):

           File "<input>", line 1, in <module>

       ValueError:list.remove(x): x not in list

8.用於反向列表中元素(該方法沒有返回值,但是會對列表的元素進行反向排序)

    L.reverse() -- reverse *IN PLACE*

       >>>l = ['shaw','sam','alice']

       >>>l.reverse()

       >>>l

       ['alice','sam', 'shaw']

9.listvalue排序(先數字,在大寫字母,小寫字母),如果指定參數,則使用比較函數指定的比較函數

    L.sort([func])

    func -- 可選參數(key和reverse, 如果指定了該參數,則會使用該參數的方法進行排序 
    
1、key在使用時必須提供一個排序過程總調用的函數:    
        x = ['mmm', 'mm', 'mm', 'm' ]
        x.sort(key = len)
        print x # ['m', 'mm', 'mm', 'mmm']
       2、reverse實現降序排序,需要提供一個布爾值:    
        y = [3, 2, 8 ,0 , 1]
        y.sort(reverse = True)
        print y #[8, 3, 2, 1, 0]

       >>>l = ['branch','sam','amy']

       >>>l.sort()

       >>>l

       ['amy','branch', 'sam']

       >>>l = [8,'branch','57','sam','amy',6]

       >>>l.sort()

       >>>l

       [6,8, '57', 'amy', 'branch', 'sam']


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章