Python3 列表

x33g5p2x  于2021-03-13 发布在 Python  
字(1.4k)|赞(0)|评价(0)|浏览(428)

Python囊括了大量的复合数据类型,用于组织其它数值。最有用的是列表,即写在方括号之间、用逗号分隔开的数值列表。列表内的项目不必全是相同的类型。

>>> 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]  # 索引返回的指定项
1
>>> squares[-1]
25
>>> squares[-3:]  # 切割列表并返回新的列表
[9, 16, 25]

所有的分切操作返回一个包含有所需元素的新列表。如下例中,分切将返回列表 squares 的一个拷贝:

>>> 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()方法在列表的末尾添加新项:

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

你也可以修改指定区间的列表值:

>>> 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
[]

内置函数 len() 用于统计列表:

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

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

>>> 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'

相关文章