python文檔:列表
3.1.3. 列表

Python 中可以通過(guò)組合一些值得到多種 復(fù)合 數(shù)據(jù)類型。其中最常用的 列表 ,可以通過(guò)方括號(hào)括起、逗號(hào)分隔的一組值(元素)得到。一個(gè) 列表 可以包含不同類型的元素,但通常使用時(shí)各個(gè)元素類型相同:
>>> squares = [1, 4, 9, 16, 25] >>> squares [1, 4, 9, 16, 25]
1
2
3
和字符串(以及各種內(nèi)置的 sequence 類型)一樣,列表也支持索引和切片:
>>> squares[0] # indexing returns the item 1 >>> squares[-1] 25 >>> squares[-3:] # slicing returns a new list [9, 16, 25]
1
2
3
4
5
6
所有的切片操作都返回一個(gè)包含所請(qǐng)求元素的新列表。 這意味著以下切片操作會(huì)返回列表的一個(gè) 淺拷貝:
>>> squares[:] [1, 4, 9, 16, 25]
1
2
列表同樣支持拼接操作:
>>> squares + [36, 49, 64, 81, 100] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
1
2
與 immutable 的字符串不同, 列表是一個(gè) mutable 類型,就是說(shuō),它自己的內(nèi)容可以改變:
>>> cubes = [1, 8, 27, 65, 125] # something's wrong here >>> 4 ** 3 # the cube of 4 is 64, not 65! 64 >>> cubes[3] = 64 # replace the wrong value >>> cubes [1, 8, 27, 64, 125]
1
2
3
4
5
6
你也可以在列表末尾通過(guò) append() 方法 來(lái)添加新元素(我們將在后面介紹有關(guān)方法的詳情):
>>> cubes.append(216) # add the cube of 6 >>> cubes.append(7 ** 3) # and the cube of 7 >>> cubes [1, 8, 27, 64, 125, 216, 343]
1
2
3
4
給切片賦值也是可以的,這樣甚至可以改變列表大小,或者把列表整個(gè)清空:
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> letters ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> # replace some values >>> letters[2:5] = ['C', 'D', 'E'] >>> letters ['a', 'b', 'C', 'D', 'E', 'f', 'g'] >>> # now remove them >>> letters[2:5] = [] >>> letters ['a', 'b', 'f', 'g'] >>> # clear the list by replacing all the elements with an empty list >>> letters[:] = [] >>> letters []
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
內(nèi)置函數(shù) len() 也可以作用到列表上:
>>> letters = ['a', 'b', 'c', 'd'] >>> len(letters) 4
1
2
3
也可以嵌套列表 (創(chuàng)建包含其他列表的列表), 比如說(shuō):
>>> a = ['a', 'b', 'c'] >>> n = [1, 2, 3] >>> x = [a, n] >>> x [['a', 'b', 'c'], [1, 2, 3]] >>> x[0] ['a', 'b', 'c'] >>> x[0][1] 'b'
1
2
3
4
5
6
7
8
9
版權(quán)聲明:本文內(nèi)容由網(wǎng)絡(luò)用戶投稿,版權(quán)歸原作者所有,本站不擁有其著作權(quán),亦不承擔(dān)相應(yīng)法律責(zé)任。如果您發(fā)現(xiàn)本站中有涉嫌抄襲或描述失實(shí)的內(nèi)容,請(qǐng)聯(lián)系我們jiasou666@gmail.com 處理,核實(shí)后本網(wǎng)站將在24小時(shí)內(nèi)刪除侵權(quán)內(nèi)容。
版權(quán)聲明:本文內(nèi)容由網(wǎng)絡(luò)用戶投稿,版權(quán)歸原作者所有,本站不擁有其著作權(quán),亦不承擔(dān)相應(yīng)法律責(zé)任。如果您發(fā)現(xiàn)本站中有涉嫌抄襲或描述失實(shí)的內(nèi)容,請(qǐng)聯(lián)系我們jiasou666@gmail.com 處理,核實(shí)后本網(wǎng)站將在24小時(shí)內(nèi)刪除侵權(quán)內(nèi)容。