Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type. Python能理解各种复合数据类型,用于将其他值分组在一起,最常用的方法就是列表,它可以用方括号括起来,用逗号分隔值(对象)的列表。列表可能包含不同类型的对象,但通常都具有相同的类型。
>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]
Like strings (and all other built-in sequence type), lists can be indexed and sliced: 与字符串操作类似,列表也可以切片(截取)操作。
>>> squares[0] # indexing returns the item 返回索引号的列表值
1
>>> squares[-1]#负数仍是从右往左
25
>>> squares[-3:] # slicing returns a new list 通过切片得到一个新的列表
[9, 16, 25]
All slice operations return a new list containing the requested elements. This means that the following slice returns a new (shallow) copy of the list: 所有的截取切片操作都返回包含请求元素的新列表。这意味着下面的截取切片返回的是新列表
>>> squares[:]
[1, 4, 9, 16, 25]
Lists also support operations like concatenation:列表还支持诸如级联的操作(即两个列表合并):
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change their content:与不可变的字符串不同,列表是可变类型,也就是说,可以改变它们的内容:
>>> cubes = [1, 8, 27, 65, 125] # something's wrong here假设这是个有规律的数列,这里就错了
>>> 4 ** 3 # the cube of 4 is 64, not 65!第四个应该是是4的三次方,不是65
64
>>> cubes[3] = 64 # replace the wrong value 用64替代错误值
>>> cubes
[1, 8, 27, 64, 125]
You can also add new items at the end of the list, by using the append() method (we will see more about methods later):您还可以通过使用AppEnter()方法在列表末尾添加新对象(稍后我们会看到更多的方法):
>>> cubes.append(216) # add the cube of 6 cube数列增加到6个对象或元素
>>> cubes.append(7 ** 3) # and the cube of 7 cube数列增加到7个对象或元素
>>> cubes
[1, 8, 27, 64, 125, 216, 343]
Assignment to slices is also possible, and this can even change the size of the list or clear it entirely 对切片(截取段)的赋值也是可能的,这甚至可以改变列表的大小或完全清除它:
>>> 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'] #2到5位为C、D、E
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them #删除
>>> letters[2:5] = [] #删除当前序号2到5位的元素
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list把列表变空
>>> letters[:] = []
>>> letters
[]
The built-in function len() also applies to lists:内置函数同样适用于列表
>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4
It is possible to nest lists (create lists containing other lists), for example: Python可以嵌套列表(创建包含其他列表的列表),例如:
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n] #嵌套
>>> x
[['a', 'b', 'c'], [1, 2, 3]] #嵌套后的结果
>>> x[0]#输出x列表的0位对象
['a', 'b', 'c']
>>> x[0][1]
'b'