其他程序语言用数组(Array)来处理,Python中则成为序列(Sequence),存放于序列中的数据称为元素(Element)或项目(item)。
序列类型可以将多个数据群聚在一起,根据其可变性(mutability)将序列分成不可变序列(Immutable Sequences)和可变序列(Mutable Sequences)。
Python通过容器(Container)进行迭代操作。迭代器(Iterator)类型是一种复合式数据类型,可将不同数据放在容器内迭代。迭代器对象会以迭代器协议(Iterator protocol)作为沟通标准。迭代器有两个接口(Interface):
Iterator(迭代器) 借助内置函数next()返回容器的下一个元素。Iterable(可迭代的) 通过内置函数iter()返回迭代器对象。 >>> data = [12,34,55] >>> num = iter(data) >>> type(num) <class 'list_iterator'> >>> next(num) 12 >>> next(num) 34 序列(Sequence)数据包含list,tuple,str。 >>> number = [10,20] >>> type(number) <class 'list'> >>> data = ('a','b','c') >>> type(data) <class 'tuple'> 序列中存放的数据成为元素(element),获取其位置,使用[]运算符配合索引编号(index)。 >>> month = ['Jan','Feb','Mar','Apr'] >>> month[2] 'Mar' >>> month[-1] 'Apr' 成员运算符in/not in >>> number = [10,20] >>> 10 in number True >>> 30 not in number True +/*运算符 >>> [20,30] + [10,20] [20, 30, 10, 20]除了数字,Python还可以处理字符串,这可以用多种方式表示。他们可以被括在单引号 ('...') 或双引号 ("...") 中,二者等价 [2]。\ 可以用于转义'︰
>>> 'spam eggs' # single quotes 'spam eggs' >>> 'doesn\'t' # use \' to escape the single quote... "doesn't" >>> "doesn't" # ...or use double quotes instead "doesn't" >>> '"Yes," he said.' '"Yes," he said.' >>> "\"Yes,\" he said." '"Yes," he said.' >>> '"Isn\'t," she said.' '"Isn\'t," she said.' 如果你不想让 \ 被解释为特殊字符开头的字符,您可以通过添加 r 使用 原始字符串︰ >>> print('C:\some\name') C:\some ame >>> print(r'C:\some\name') C:\some\name 内置函数enumerate()提供索引 >>> word = 'good' >>> print(list(enumerate(word))) [(0, 'g'), (1, 'o'), (2, 'o'), (3, 'd')] word = 'good' for id, data in enumerate(word): print([id], data, end=' ') [0] g [1] o [2] o [3] d