
3.2.1 Python的列表
Python所特有的类型的成员或者所包含的元素是有序排列的,并且允许用户通过下标偏移量访问到它所包含的元素或成员。Python可以通过给定元素的办法初始化一个列表,也可以通过迭代器和for循环语句自动生成有序的元素组作为列表,示例如下:

输出结果:

在该示例中使用了is语句判断lis和lis2是否为同一个变量。用户还可以用in和not in判断列表中是否包含某个元素,或者是否不含某个元素,示例如下:


输出结果:

如果需要将一个序列重复多次,则可以使用星号(*)运算符。在下面的示例中,1~5这个序列重复了3次。

输出结果:

Python的列表作为一种数据类型,其中的元素按顺序依次放置。作为数组的“替代品”,它一定会有与数组类似的功能,即依照下标读取列表中存放的元素。不仅如此,Python的列表还可以通过类似字符串切片算法的原理,提取列表中一连串的元素,这是C/C++和Java所不能实现的。这种方式称为“切片操作”或“索引操作”,用中括号“[]”来表示,具体的语法如下:

List是被操作的列表;startIndex是切片开始的序号;endIndex是切片结束的序号;stepNumber是切片的间隔(或步长),默认为1,可以与第二个冒号一起省略。startIndex的默认值是0,可省略不写,即从第一个序号开始切片;endIndex默认是最后一个元素,序号是-1,使用的是逆序序列的索引。正序索引从0开始到n-1;而逆序索引从-1开始到-n。Python的列表的索引规则如图3-2所示。

图3-2 Python的列表的索引规则
Python切片操作的简单示例如下所示。

输出结果:


切片操作还可以和for循环语句结合使用,这里以输出一个金字塔的程序为例进行介绍,代码如下:

输出结果:


Python的列表的内建函数如表3-4所示。
表3-4 Python的列表的内建函数
