本系列是学习 廖雪峰 Python3 教程 过程中记录的笔记,本篇文章记录 Python
的一些高级特性,包括切片操作、迭代操作、列表生成式的使用,以及生成器和迭代器。
高级特性
切片
-
适用于
List
Tuple
和字符串,操作灵活; -
[start_index : end_index : step_size]
省略
start_index
,包含该索引,默认从 0 开始;省略
end_index
, 不包含该索引,默认到最后一位截至;省略
step_size
,默认步长为 1 ;L = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(L[0:2]) print(L[0:6:2]) print(L[0:6:3]) print(L[-4:-1]) print(L[-4:-1:2]) print(L[::]) output———————— [0, 1] [0, 2, 4] [0, 3] [6, 7, 8] [6, 8] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
迭代
-
适用于所有可迭代对象,常见的数据类型有
List
Tuple
Dict
Set
和 字符串,对于Tuple
Dict
由于元素无序,迭代出的结果很可能也是无序的。 -
for value in dict.values()
访问所有的value
; -
for k, v in dict.items()
可同时访问key
和value
; -
for i, value in enumerate(list)
可同时访问index
和value
;d = {'a': 1, 'b': 2, 'c': 3} for value in d.values(): print(value) for key, value in d.items(): print(key, ":", value) L = ["wang", "tian", "liang"] for index, value in enumerate(L): print(index, ":", value) str = "i love u" for ch in str: print(ch) output———————— 1 2 3 a : 1 b : 2 c : 3 0 : wang 1 : tian 2 : liang i l o v e u
列表生成式
-
range(start_index, end_index, step_size)
返回整数列表; -
[x * y for x in range(0, 6, 5) for y in range(1, 3)]
基本上两层循环就可以满足绝大部分需求了,简化代码; -
[x for x in range(0, 5) if x % 2 == 0]
生成式中的if
用于筛选合适的值; -
生成式中还可以与
d.items()
内置函数等结合;L = [x * y for x in range(0, 6, 5) for y in range(1, 3)] print(L) L = [x for x in range(0, 5) if x % 2 == 0] print(L) d = {'x': 'A', 'y': 'B', 'z': 'C'} L = [k + '=' + v for k, v in d.items()] print(L) L = ['Hello', 'World', 'IBM', 'Apple'] l = [s.lower() for s in L] print(l) output———————— [0, 0, 5, 10] [0, 2, 4] ['x=A', 'y=B', 'z=C'] ['hello', 'world', 'ibm', 'apple']
生成器
-
一边循环一边计算的机制,可以节省大量空间;
-
列表生成器,仅需要将
[]
换成()
即可,使用for
循环迭代访问,也可以使用next()
依次访问; -
函数生成器,带有
yield
关键字,此时调用该函数时需要先生成一个函数对象,每次使用next()
执行,遇到yield
就中断执行,下次执行时从上次中断位置继续; -
函数生成器的返回值包含在
StopIteration
错误的value
中。g = (x * x for x in range(3)) print(type(g)) for n in g: print(n) def fib(max): # 斐波拉契数列生成器 n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1 return 'done' g = fib(4) while True: try: x = next(g) print('g:', x) except StopIteration as e: print('Generator return value:', e.value) break output—————————— <class 'generator'> 0 1 4 g: 1 g: 1 g: 2 g: 3 Generator return value: done
迭代器
-
凡是可作用于
for
循环的对象都是Iterable
类型,使用isinstance()
判断一个对象是否是Iterable
对象; -
凡是可作用于
next()
函数的对象都是Iterator
类型,它们表示一个惰性计算的序列; -
集合数据类型如
list
、dict
、str
等是Iterable
但不是Iterator
,不过可以通过iter()
函数获得一个Iterator
对象; -
非迭代器的可迭代对象在使用for循环时,实际是先调用
iter()
方法转换为迭代器,再循环调用 next()并返回值。from collections import Iterable print(isinstance([], Iterable)) print(isinstance({}, Iterable)) print(isinstance((), Iterable)) print(isinstance('abcd', Iterable)) print(isinstance(100, Iterable)) for x in [3, 4, 5]: print(x) it = iter([3, 4, 5]) # 首先获得Iterator对象 while True: try: x = next(it) # 获得下一个值 print("iter:", x) except StopIteration: # 遇到StopIteration就退出循环 break output——————————— True True True True False 3 4 5 iter: 3 iter: 4 iter: 5