Python——列表的方法

在Python中有六種內建的序列:列表、元組、字符串、Unicode字符串、buffer對象和xrange對象。在這裏只討論關於Python中列表的定義:

在Python中沒有所謂數組的概念,但是在Python中列表與數組很相像。列表的數據項不需要具有相同的數據類型。列表中的每個元素都分配一個數字 -即它的位置,第一個數據類型在列表中的位置是0,第二個數據類型在列表中的位置是1,依此類推。

1. 創建一個列表:

>>> list1 = ['hello','world']
>>> list2 = ['Any',123]

>>> list3 = [123,456]

2. 列表大致有四種操作,分別爲增、減、修、排

增:

  1.使用append,默認將所添加的內容排到列表的最後一項

數組名.append(添加的內容)

 >>> list1.append('Any')
>>> list1
['hello', 'world', 'Any']

   2.使用insert,可以將所要添加的內容添加到列表的任意一項內容之後

數組名.insert(任意一項的下標加1,添加的內容)

>>> list2.insert(1,'girl')
>>> list2
['Any', 'girl', 123]

3. 使用extend,默認將所添加的內容排到列表的最後一項

>>> list3.extend('hello')
>>> list3
[123, 456, 'h', 'e', 'l', 'l', 'o']

 修

1.通過知道所要修改內容的下標,而對內容進行一個一個修改

>>> list4 = ['hello','Any']
>>> list4[1] = 'world'
>>> list4
['hello', 'world']

 2.所要修改的內容在一塊,而且大於1個以上

>>> list5 = ['Any','gril',26,'music']
>>> list5[1:3] = ['boy',43]
>>> list5
['Any', 'boy', 43, 'music']

排:

1.使用sort,對數據按照其在ASCII中所排的位置進行排序

>>> list2=[121,120,3525,90834]
>>> list2.sort()
>>> list2
[120, 121, 3525, 90834]

 >>> list1 = ['sadj','assge','asaue']
>>> list1.sort()
>>> list1
['asaue', 'assge', 'sadj']

而在使用sort時,列表中不能出現兩種不同的數據類型 

>>> list1 = ['any',23,'hello']
>>> list1.sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'int' and 'str' 

 2.使用reverse,對數據按照其在ASCII中所排的位置進行排序

>>> list1 = [12,9,926]
>>> list1.reverse()
>>> list1
[926, 9, 12]

 >>> list2 = ['any','Gril','python']
>>> list2.reverse()
>>> list2
['python', 'Gril', 'any']

如果列表裏含有兩種不同的數據類型,則會報錯 

 >>> list3 = ['any',123,'ash']
>>> list.reverse()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: descriptor 'reverse' of 'list' object needs an argument

 刪:

1.使用remove,可對列表中的任意元素進行刪除

>>> list1 = ['Any',23,'boy']

>>> list1.remove(23)
>>> list1
['Any', 'boy']

 2.使用pop,對列表中的元素進行刪除,所刪除的元素會返還給你,但是刪除前必須知道所要刪除的元素在列表中的位置

>>> list2 = ['hello','Any','boy']

>>> list2.pop(2)
'boy'
>>> list2
['hello', 'Any']

 3.使用clear,對列表中的元素進行全部刪除

 >>> list3 = ['Python','hello','book']

 >>> list3.clear()
>>> list3
[]

 4.使用del,可對列表中的元素進行單個刪除,也可對列表中的元素進行全部刪除

>>> list3 = [1342,7286,'ajakjd']
>>> del list3[2]
>>> list3
[1342, 7286]
>>> del list3
>>> list3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'list3' is not defined

 

 

 

 

 

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