1. 程式人生 > >list內建函式梳理

list內建函式梳理

函式名:append

#將單個項新增到現有列表中。它不會返回一個新的列表;相反,它修改了原始列表。

>>> a=[1]

>>> a.append(2)

>>> a

[1, 2]

L.append(object) -> None -- appendobject to end

函式名:clear

#clear()方法從列表中刪除所有項。

>>> b
[1, 2, 3, 1, 5, 6]
>>> b.clear()
>>> b
[]

L.clear() -> None -- remove all itemsfrom L

函式名:copy

#返回列表的一個淺拷貝。

>>> a=[1,2,3,1,5,6]
>>> b=a.copy()
>>> a=[1,2,3,1,5,6]
>>> b=a.copy()

L.copy() -> list -- a shallow copy of L

函式名:count

#count()方法返回列表中元素的出現次數。

>>> a=[1,2,3,1,5,6]
>>> a.count(1)
2

L.count(value) -> integer -- return numberof occurrences of value


函式名:extend

#擴充套件列表,將列表的所有項(作為引數傳遞)新增到末尾。

>>> language = ['French', 'English', 'German']
>>> language1 = ['Spanish', 'Portuguese']
>>> language.extend(language1)
>>> language
['French', 'English', 'German', 'Spanish', 'Portuguese']

L.extend(iterable) -> None -- extendlist by appending elements from the iterable

函式名:index

#index()方法在列表中搜索一個元素並返回它的索引。

#索引方法採用單個引數:元素——要搜尋的元素。不存在會報錯

>>> a=[1,2,3,4,5,6]
>>> a.index(3)
2
>>> a.index(7)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: 7 is not in list

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

Raises ValueError if the value is notpresent.

函式名:insert

#insert()方法將元素插入到給定索引的列表中。

insert()函式包含兩個引數:

索引——需要插入元素的位置。

元素——這是要插入到列表中的元素。

>>> a=[1,2,3,4,5,6]
>>> a.insert(1,'a')
>>> a
[1, 'a', 2, 3, 4, 5, 6]

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

函式名:pop

#pop()方法從列表中刪除並返回給定索引中的元素(作為引數傳遞)。

pop()方法採用單個引數(index),並從列表中刪除該索引中的元素。

如果傳遞給pop()方法的索引不在範圍內,它會丟擲IndexError: pop索引超出範圍異常。

傳遞給pop()方法的引數是可選的。如果沒有傳遞引數,則將預設索引-1作為引數傳遞,以返回最後一個元素。

>>> a=[1,2,3,1,5,6]
>>> a.pop(3)
1
>>> a.pop()
6
>>> a
[1, 2, 3, 5]

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

Raises

L.sort(key=None, reverse=False) -> None-- stable sort *IN PLACE*


IndexError if list is empty or indexis out of range.

函式名:remove

#remove()方法搜尋列表中的給定元素並刪除第一個匹配元素。

remove()方法將單個元素作為引數,並將其從列表中刪除。

如果傳遞給remove()方法的元素(引數)不存在,則丟擲valueError異常。

>>> a=[1,2,3,4,5,6]
>>> a.remove(2)
>>> a
[1, 3, 4, 5, 6]
>>> a.remove(7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list

L.remove(value) -> None -- remove firstoccurrence of value.

Raises ValueError if the value is notpresent.

函式名:reverse

#反轉給定列表的元素。

#函式的作用是:不返回任何值。它只返回元素並更新列表。

>>> a=[1,2,3,1,5,6]
>>> a.reverse()
>>> a
[6, 5, 1, 3, 2, 1]

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

函式名:sort

#對給定列表的元素進行排序。

預設情況下,sort()不需要任何額外的引數。但是,它有兩個可選引數:

reverse——預設為False,排序列表將被反向(或按降序排序)

key-函式,作為排序比較的引數。

def takeSecond(elem):
    return elem[1]
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
random.sort(key=takeSecond)
print('Sorted list:', random)
Sorted list: [(4, 1), (2, 2), (1, 3), (3, 4)]

L.sort(key=None, reverse=False) -> None-- stable sort *IN PLACE*