
上QQ阅读APP看书,第一时间看更新
2.2 列表及操作
2.2.1 列表及其创建
在实际开发中,经常需要将一组(不止一个)数据存储起来,以便后边的代码使用。很多高级语言都有数组(array),可以把多个数据连续存储到一起,通过数组下标可以访问数组中的每个元素。需要明确的是,Python中没有数组,但是加入了更加强大的列表。如果把数组看作是一个集装箱,那么Python的列表就是一个工厂的仓库。
从形式上看,列表会将所有的元素都放在一对中括号“[ ]”里面,相邻元素之间用逗号“,”分隔,如下所示:

格式中,element1~elementn表示列表中的元素,个数没有限制,只要是Python支持的数据类型就可以。
从内容上看,列表可以存储整数、小数、字符串、列表、元组等任何类型的数据,并且同一个列表中元素的类型也可以不同,例如:

可以看到,列表中同时包含字符串、整数、列表、浮点数这些数据类型。在使用列表时,虽然可以将不同类型的数据放到同一个列表中,但通常情况下同一列表中只放入同一类型的数据,这样可以提高程序的可读性。
在Python中,创建列表的方法可分为以下两种。
(1)使用“[ ]”直接创建列表
使用“[ ]”创建列表后,一般使用“=”将它赋值给某个变量,具体格式如下:

其中,listname表示变量名,element1~elementn表示列表元素。
【例2-7】 定义合法的列表。

例中,emptylist是一个空列表。
(2)使用list()函数创建列表
除了使用“[ ]”创建列表外,Python还提供了一个内置的函数list(),使用它可以将其他数据类型转换为列表类型。
【例2-8】 使用list()函数创建多个列表。


运算结果:
