❶ Python中列表的方法有什麼
Python中的列表內建了許多方法。在下文中,使用「L」代表一個列表,使用「x」代表方法的參數,以便說明列表的使用方法。
1 append()方法
列表的append()方法用於將一個項添加到列表的末尾,L.append(x)等價於L[len(L):] = [x]。
例如,使用append()方法分別將'cow'和'elephant'添加到animals列表的末尾:
>>>animals=['cat','dog','fish','dog']
>>>animals.append('cow')#等價於animals[4:]=['cow']
>>>animals
['cat','dog','fish','dog','cow']
>>>animals.append('elephant')#等價於animals[5:]=['elephant']
>>>animals
['cat','dog','fish','dog','cow','elephant']
2 ()方法
列表的()方法用於將一個項插入指定索引的前一個位置。L.(0, x)是將x插入列表的最前面,L.(len(L)), x)等價於L.append(x)。
例如,使用()方法分別將'cow'和'elephant'插入animals列表:
>>>animals=['cat','dog','fish','dog']
>>>animals.(0,'cow')
>>>animals
['cow','cat','dog','fish','dog']
>>>animals.(3,'elephant')
>>>animals
['cow','cat','dog','elephant','fish','dog']
3 extend()方法
列表的extend()方法用於將可迭代對象的所有項追加到列表中。L.extend(iterable)等價於L[len(L):] = iterable。extend()和append()方法的區別是,extend()方法會將可迭代對象「展開」。
例如,分別使用append()方法和extend()方法在animals列表後面追加一個包含'cow'和'elephant'的列表:
>>>animals=['cat','dog','fish','dog']
>>>animals.append(['cow','elephant'])#此處append()參數是一個列表
>>>animals
['cat','dog','fish','dog',['cow','elephant']]
>>>animals=['cat','dog','fish','dog']
>>>animals.extend(['cow','elephant'])#此處extend()參數也是一個列表
>>>animals
['cat','dog','fish','dog','cow','elephant']
4 remove()方法
列表的remove()方法用於移除列表中指定值的項。L.remove(x)移除列表中第一個值為x的項。如果沒有值為x的項,那麼會拋出ValueError異常。
例如,使用remove()方法移除animals列表中值為'dog'的項:
>>>animals=['cat','dog','fish','dog']
>>>animals.remove('dog')
>>>animals
['cat','fish','dog']
>>>animals.remove('dog')
>>>animals
['cat','fish']
>>>animals.remove('dog')
Traceback(mostrecentcalllast):
File"",line1,in
ValueError:list.remove(x):xnotinlist
5 pop()方法
列表的pop()方法用於移除列表中指定位置的項,並返回它。如果沒有指定位置,那麼L.pop()移除並返回列表的最後一項。
例如,使用pop()方法移除animals列表中指定位置的項:
>>>animals=['cat','dog','fish','dog']
>>>animals.pop()
'dog'
>>>animals
['cat','dog','fish']
>>>animals.pop(2)
'fish'
>>>animals
['cat','dog']
在調用前面的列表方法後,並沒有列印任何值,而pop()方法列印了「彈出」的值。包括append()、()、pop()在內的方法都是「原地操作」。原地操作(又稱為就地操作)的方法只是修改了列表本身,並不返回修改後的列表。
在類型轉換時使用的int()函數,str()函數都有返回值:
>>>number=123
>>>mystring=str(number)#將返回值賦給變數mystring
>>>mystring
'123'
但是在使用「原地操作」時,大部分則不會有返回值,包括pop()方法也只是返回了被「彈出」的值,並沒有返回修改後的列表:
>>>animals=['cat','dog','fish','dog']
>>>new_animals=animals.append('cow')
>>>print(new_animals)
None
關於Python的基礎問題可以看下這個網頁的視頻教程,網頁鏈接,希望我的回答能幫到你。
❷ Python中最常用的操作列表的幾種方法歸納
這里介紹幾個常用的列表操作:
1、添加元素
添加元素使用列表的內置方法append
number = [1, 2, 3, 4]
number.append(5) # number = [1, 2, 3, 4, 5]
number.append([6,7]) # number = [1, 2, 3, 4, 5, [6, 7]]
number.append({'a':'b'}) # number = [1, 2, 3, 4, [6, 7], {'a', :'b'}
可以看到強大的python列表可以嵌套任意類型
2、列表相加
要想連接兩個列表,可以使用+號連接
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b # c = [1, 2, 3, 4, 5, 6]
也可以使用列表內置方法extend連接兩個列表
a = [1, 2, 3]
b = [4, 5, 6]
a.extend(b) # a = [1, 2, 3, 4, 5, 6]
用+號會創建一個新通對象,使用extend則在原來的對象上面修改
3、列表去重復
列表本身沒有去除重復的功能,但是可以藉助python的另外一個類型set(help(set)查看)
a = [1, 2, 3, 3,2, 1]
b = list(set(a)) # b = [1, 2, 3]
也可以藉助字典類型的內置方法
a = [1, 2, 2, 3, 1, 3]
b = {}.fromkeys(a).keys() # b = [1, 2, 3]