列表(List)是最基本的Python数据结构,是通过对数据元素进行编号将它们组织在一起的数据元素的集合。 列表可以进行的操作包括索引,切片,加,乘,检查成员。
此外,Python已经内置确定列表的长度以及确定最大和最小元素的方法。
创建一个列表,只要把逗号分隔的不同数据项使用方括号括起来即可。如下所示:
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
[1, 2, 3]
[1, 2, 3]
['cat', 'bat', 'rat', 'elephant']
['cat', 'bat', 'rat', 'elephant']
['hello', 3.1415, True, None, 42]
['hello', 3.1415, True, None, 42]
spam = ['cat', 'bat', 'rat', 'elephant']
spam
['cat', 'bat', 'rat', 'elephant']
spam
变量仍然只被赋予一个值:列表值。但列表值本身包含多个值。
[]
是一个空列表,不包含任何值,类似于空字符串。
spam = ['cat', 'bat', 'rat', 'elephant']
spam[0]
'cat'
spam[1]
'bat'
spam[2]
'rat'
spam[3]
'elephant'
['cat', 'bat', 'rat', 'elephant'][3]
'elephant'
'Hello '+ spam[0]
'Hello cat'
'The ' + spam[1] + ' ate the ' + spam[0] + '.'
'The bat ate the cat.'
请注意,表达式 'Hello'+ spam[0]
求值为'Hello'+'cat'
,
因为spam[0]
求值为字符串 'cat'
。
这个表达式也因此求值为字符串'Hello cat'
。
如果使用的下标超出了列表中值的个数, Python 将给出 IndexError
出错信息。
# spam = ['cat', 'bat', 'rat', 'elephant']
# spam[10000] #此代码会报错
下标只能是整数,不能是浮点值。下面的例子将导致 TypeError
错误:
spam = ['cat', 'bat', 'rat', 'elephant']
spam[1]
'bat'
# spam[1.0] #此代码会报错
spam[int(1.0)]
'bat'
列表也可以包含其他列表值。这些列表的列表中的值,可以通过多重下标来访问,像这样:
spam = [['cat', 'bat'], [10, 20, 30, 40, 50]]
spam[0]
['cat', 'bat']
spam[0][1]
'bat'
spam[1][4]
50
spam = ['cat', 'bat', 'rat', 'elephant']
spam[-1]
'elephant'
spam[-3]
'bat'
'The ' + spam[-1] + ' is afraid of the ' + spam[-3] + '.'
'The elephant is afraid of the bat.'
spam = ['cat', 'bat', 'rat', 'elephant']
spam[0:4]
['cat', 'bat', 'rat', 'elephant']
spam[1:3]
['bat', 'rat']
spam[0:-1]
['cat', 'bat', 'rat']
作为快捷方法,可以省略切片中冒号两边的一个下标或两个下标。
省略第一个下标相当于使用 0
,或列表的开始。
省略第二个下标相当于使用列表的长度,
意味着分片直至列表的末尾。在交互式环境中输入以下代码:
spam = ['cat', 'bat', 'rat', 'elephant']
spam[:2]
['cat', 'bat']
spam[1:]
['bat', 'rat', 'elephant']
spam[:]
['cat', 'bat', 'rat', 'elephant']