Python 列表

Python 中可以通过组合一些值得到多种 复合 数据类型。其中最常用的 列表 ,可以通过方括号括起、逗号分隔的一组值得到。一个 列表 可以包含不同类型的元素,但通常使用时各个元素类型相同:

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


和字符串及各种内建的 sequence 类型一样,列表也支持索引和切片:

>>> squares[0]  # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:]  # slicing returns a new list
[9, 16, 25]


所有的切片操作都返回一个新列表,这个新列表包含所需要的元素。就是说,如下的切片会返回列表的一个新的(浅)拷贝:

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


列表同样支持拼接操作:

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


与 immutable 的字符串不同, 列表是一个 mutable 类型,就是说,它自己的内容可以改变:

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


你也可以在列表结尾,通过 append() 方法 添加新元素 (我们会在后面解释更多关于方法的内容):

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


给切片赋值也是可以的,这样甚至可以改变列表大小,或者把列表整个清空:

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


Python 内置函数 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'


原文地址:https://www.cnblogs.com/yuanrenxue/p/10694850.html