列表是指一組數據有序的排列方式,可以通過索引的方式來訪問數據。列表是可修改的。
1.創建列表
列表中的數據可是任意類型,包括整數、浮點數、字符串、列表、元組,字典等
list1=[1,2,3,4,5,6] list2=['a','b','c',5,6,7,[1,2,3,4]]
修改列表
list1=[1,2,3,4] list1[0]=999 print list1 [999, 2, 3, 4]
2.訪問列表
列表訪問與字符串一致。
list1=[1,2,3,4,5] list1[0] 1 list1[-3] 3
3.切片
列表的切片與字符串相同。
list1[1:-3] [2] list1[1:-1] [2, 3, 4] list1[:] [1, 2, 3, 4, 5] list1[9:] []
4、列表的方法
a. append向列表尾部增加一個元素
格式:L.append(object) -- append object to end
>>> l=[1,2,3,4,5] >>> print l [1, 2, 3, 4, 5] >>> l.append(0) >>> print l [1, 2, 3, 4, 5, 0]
b. count列表中一個元素出現的次數(有返回值)
格式:L.count(value) -> integer -- return number of occurrences of value
>>> l=[1,2,1,2,1,2,1,2] >>> l.count(1) 4 >>> l.count(2) 4
c. extend向列表中追加一個列表(元組)
格式:L.extend(iterable) -- extend list by appending elements from the iterable
>>> l=[1,2,3,4,5]
>>> b=[1,2,3] >>> l.extend(b) >>> print l [1, 2, 3, 4, 5, 1, 2, 3] >>> b=(6,6,6) >>> l.extend(b) >>> l [1, 2, 3, 4, 5, 1, 2, 3, 6, 6, 6]
d. index顯示列表中元素的索引位置,如果不存在報異常.
格式:L.index(value, [start, [stop]]) -> integer -- return first index of value.
>>> l=[1,2,3,4,5] >>> l.index(4) 3 >>> l.index(7) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: 7 is not in list 在這裏index用法中,可在指定元素之後指定索引位置 >>> l.index(4,3,5) 3 >>> l.index(4,4,5) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: 4 is not in list
e. instert 插入一個元素
格式:L.insert(index, object) -- insert object before index>>> l
[1, 2, 3, 4, 5] >>> l.insert(2,9) >>> print l [1, 2, 9, 3, 4, 5]
2指索引位置爲2位置的元素,在其後插入9
f. pop刪除最後一個元素,有返回值
格式: L.pop([index]) -> item -- remove and return item at index (default last).
>>> l=[1,2,3,4,5] >>> l.pop() 5 >>> print l [1, 2, 3, 4]
g. remove刪除指定元素,不存在則報異常
格式:L.remove(value) -- remove first occurrence of value.
>>> print l [1, 2, 3, 4] >>> l.remove(2) >>> print l [1, 3, 4] >>> l.remove(9) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: list.remove(x): x not in list
h. reverse列表反轉
格式:L.reverse() -- reverse *IN PLACE*
>>> print l [1, 2, 3, 4, 5, 6] >>> l.reverse() >>> print l [6, 5, 4, 3, 2, 1] >>>
i. sort列表排序
格式:L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
cmp可以指定一個函數,key可以指定排序的依據,reverse是指排列順序,默認False從小到大。
>>> l=[3,5,6,2,4,1,9] >>> l.sort() >>> print l [1, 2, 3, 4, 5, 6, 9]
從大到小排序
>>> l=[3,5,6,2,4,1,9] >>> l.sort(reverse=True) >>> l [9, 6, 5, 4, 3, 2, 1]
依據字符串長短排序
>>> l=["c","www","aaaa","aa","ee"] >>> l.sort(key=len) >>> print l ['c', 'aa', 'ee', 'www', 'aaaa']
默認排序
>>> l=["c","www","aaaa","aa","ee"] >>> l.sort() >>> print l ['aa', 'aaaa', 'c', 'ee', 'www']
總結:列表的用法相對於字符串少,也簡單,但列表同字符串一樣重要。列表是可修改的,這一點十分重要,看完這篇文章後大家可以想想列表與字符串如何轉化,在上一章文章中是有介紹的哦,忘記了的話可以看看上一篇文章。