亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

文字

Python 列表


Python囊括了大量的復(fù)合數(shù)據(jù)類型,用于組織其它數(shù)值。最有用的是列表,即寫在方括號(hào)之間、用逗號(hào)分隔開的數(shù)值列表。列表內(nèi)的項(xiàng)目不必全是相同的類型。

>>> a = ['spam', 'eggs', 100, 1234]
>>> a
['spam', 'eggs', 100, 1234]
>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

像字符串一樣,列表可以被索引和切片:

<pre>
>>> squares[0]  # 索引返回的指定項(xiàng)
1
>>> squares[-1]
25
>>> squares[-3:]  # 切割列表并返回新的列表
[9, 16, 25]

所有的分切操作返回一個(gè)包含有所需元素的新列表。如下例中,分切將返回列表 squares 的一個(gè)拷貝:

>>> squares[:]
[1, 4, 9, 16, 25]

列表還支持拼接操作:

>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Python 字符串是固定的,列表可以改變其中的元素:

>>> cubes = [1, 8, 27, 65, 125]   
>>> 4 ** 3  
64
>>> cubes[3] = 64  # 修改列表值
>>> cubes
[1, 8, 27, 64, 125]

您也可以通過使用append()方法在列表的末尾添加新項(xiàng):


>>> cubes.append(216)  # cube列表中添加新值
>>> cubes.append(7 ** 3)  #  cube列表中添加第七個(gè)值
>>> cubes
[1, 8, 27, 64, 125, 216, 343]

你也可以修改指定區(qū)間的列表值:

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # 替換一些值
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # 移除值
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # 清楚列表
>>> letters[:] = []
>>> letters
[]

內(nèi)置函數(shù) len() 用于統(tǒng)計(jì)列表:

>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4

也可以使用嵌套列表(在列表里創(chuàng)建其它列表),例如:

>>> 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'
上一篇: 下一篇: