1. 程式人生 > 其它 >第六章、Python資料型別(list列表)

第六章、Python資料型別(list列表)

列表(List)

python中用方括號 [ ] 表示一個list,方括號裡面可以是各種資料型別。

>>> a=[1,'q',True]
>>> type(a)
<type 'list'>

1)列表也有類似字串一樣的索引和切片,方法一樣

>>> a=[1,23,2]
>>> a[0]
1
>>> a.index(1)
0

2)反轉:字串倒過來。

反轉,不是在“原地”把原來的值倒過來,而是新生成了一個值,那個值跟原來的值相比,是倒過來了,原來的值還存在於變數中

反轉有兩種方式:

>>> a=[1,23,2]
>>> a[::-1]          #方式一
[2, 23, 1]
>>>a
[1,23,2]
>>> list(reversed(a))   #方式二
[2, 23, 1]

3)基礎操作

>>> a.append("like")       #增加列表元素,追加到尾部
>>> a
[1, 23, 2, 'like']
>>> b=['q', 'w']
>>> a.extend(b)   #b中的所有元素加入到a中
>>> a
[1, 2, 3, 'q', 'w']
>>> b
['q', 'w']

>>> a = "python"
>>> hasattr(a,'__iter__')  
False
>>>b = [1,2]
>>> hasattr(b,'__iter__')  
True
#hasattr()判斷一個字串是否是可迭代的,是返回True,否返回False。其判斷本質就是看該型別中是否有__iter__函式。用dir()查詢整型、字串、列表中,誰有__iter__。
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

#id()函式檢視變數在記憶體的位置編碼
>>> id(a)
140571421973464
>>> id(b)
140571377764352

4)insert(i, x)函式,含義是將元素 x 插入到索引值是 i 的元素前面。索引值是從0開始的。

>>> a=['a','b','c','d']
>>> a.insert(2,'q')
>>> a
['a', 'b', 'q', 'c', 'd']
>>> a.insert(9,'w')
>>> a
['a', 'b', 'q', 'c', 'd', 'w']

注:當 i 的值大於 list 中的最大索引值時,元素 x 自動插入 list 末尾。

5)remove(x)函式,刪除列表中的x元素。注:當列表中含有多個不緊鄰的x元素時,只刪除第一個x元素,若相鄰的就一起刪除

>>> a=['a', "a",'b', 'c', 'd', 'w']
>>> a.remove('a')
>>> a
['a', 'b', 'c', 'd', 'w']
>>> a=['a','b','a', 'c', 'd', 'w']
>>> a.remove('a')
>>> a
['b', 'a', 'c', 'd', 'w']

6)pop(i)函式,刪除指定索引值 i 對應的元素,並將刪除結果返回,若不寫 i , 預設刪除最後一個元素。

>>> a=['b', 'a', 'c', 'd', 'w']
>>> a.pop()
'w'
>>> a
['b', 'a', 'c', 'd']
>>> a.pop(2)
'c'

7)reverse()函式,將列表反轉,等同於 list[ : :-1]

>>> a=['a','b','c']
>>> a.reverse()
>>> a
['c', 'b', 'a']
>>> a[::-1]
['a', 'b', 'c']

8)sort()函式,對原列表進行排序,語法:

list.sort(cmp=None,key=None,reverse=False)   #python 2.x
list.sort( key=None, reverse=False)     #python 3.x

key -- 主要是用來進行比較的元素,只有一個引數,具體的函式的引數就是取自於可迭代物件中,指定可迭代物件中的一個元素來進行排序。預設值None

reverse -- 排序規則,reverse = True降序,reverse = False升序(預設)。

>>> a=['qwe','rty','uiop']
>>> a.sort()
>>> a
['qwe', 'rty', 'uiop']
>>> a.sort(key=len)
>>> a
['qwe', 'rty', 'uiop']
>>> a.sort(key=len,reverse=True)
>>> a
['uiop', 'qwe', 'rty']
>>> b=[45,5,7,3]
>>> b.sort()
>>> b
[3, 5, 7, 45]

此外,還有一個內建函式sorted()用於排序

sorted(iterable,cmp=None,key=None,reverse=False)#python 2.x
sorted(iterable,key=None,reverse=False) #python 3.x
注:兩函式的的區別是, sort( )函式時是在原列表上進行排序,無返回值;而sorted( )函式是返回一個新的list,不在原來的list上進行操作,呼叫其返回一個排好序的list。
>>> b
[3, 5, 7, 45]
>>> c=sorted(b)
>>> c
[3, 5, 7, 45]

9)split()函式,指定分隔符對字串進行分割,分割後的字串以逗號“,”隔開。

語法:str.split(str="", num=string.count(str))

  • str -- 分隔符,預設為所有的空字元,包括空格、換行(\n)、製表符(\t)等。
  • num -- 分割次數。分隔出 num+1 個子字串,預設為 -1, 即分隔所有。
>>> a="hello world to you"
>>> a.split()
['hello', 'world', 'to', 'you']
>>> a
'hello world to you'
>>> a.split(" ",1)
['hello', 'world to you']
>>> a.split(" ",2)
['hello', 'world', 'to you']

10)join() 函式用於將序列中的元素以指定的字元連線生成一個新的字串。

語法:str.join(sequence)

str:指定字元 sequence:序列名

>>> a,b=(1,2,3,4,5),['a','b','c','d']
>>> "".join(b)
'abcd'
>>> "".join(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found
>>> print(" ".join('%s' %id for id in a))
1 2 3 4 5
>>> " ".join('%s' %id for id in a)
'1 2 3 4 5'

注:若序列中元素包含數字,則join()會報錯。需遍歷序列中元素,將之轉化成字串。這樣就能成功輸出數字結果。

11)remove()函式,刪除列表中的某個元素

>>> b=[1,2,3]
>>> b.remove(2)
>>> b
[1, 3]

Python的序列型別:字串、列表、元組