---恢复内容开始---
一、切片(list、tuple、str)
L = list(range(100))
>>> L[:3] ##取前3个 L[0:3]
>>> L[-2:] ## 取倒数两个
>>> L[-1】 ## 取倒数第一个
>>> L[:10:2] ## 前10个数,每两个取一个
[0, 2, 4, 6, 8]
>>> L[::5] ## 所有数,每5个取一个
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
>>> L[:] ##原样复制一个list
[0, 1, 2, 3, ..., 99]
>>> L[::-1] ##取反序列
二、迭代
for ... in <可迭代对象>:
1、判断是否可迭代对象Iterable
list、tuple、dict、set、str
>>> from collections import Iterable
>>> isinstance('abc', Iterable) # str是否可迭代
True
>>> isinstance([1,2,3], Iterable) # list是否可迭代
True
>>> isinstance(123, Iterable) # 整数是否可迭代
False
2、dict迭代,默认迭代key
>>> for key in d:
>>> for value in d.values():
>>> for k,v in d.items():
三、列表生成器List Comprehensions
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> [x * x for x in range(1, 11) if x % 2 == 0]
[4, 16, 36, 64, 100]
使用两层循环,可以生成全排列:
>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
列表生成式也可以使用两个变量来生成list:
>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> [k + '=' + v for k, v in d.items()]
['y=B', 'x=A', 'z=C']
四、生成器generator
>>> L = [x * x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> g = (x * x for x in range(10))
>>> for n in g:
... print(n)
generator函数,遇到yield关键字返回,不继续执行函数,再次调用函数,从yield语句之后继续执行
def odd():
print('step 1')
yield 1
print('step 2')
yield(3)
print('step 3')
yield(5)
##调用函数
>>> o = odd()
>>> next(o)
step 1
1
>>> next(o)
step 2
3
>>> next(o)
step 3
5
>>> next(o)
Traceback (most recent call last):
File "", line 1, in
StopIteration ## 超出范围,报错
可以产生无限序列
## 构造从3开始的奇数序列
def _odd_iter():
n = 1
while True:
n = n + 2
yield n
五、迭代器Iterator
①可以被next()函数调用并返回下一个值,直到抛出 StopIteration错误
②生成器 generator都是迭代器Iterator
③list、dict、str是可迭代对象Iterable,但不是迭代器Iterator,用iter()可以把可迭代对象Iterable变成迭代器Iterator