一、切片(适用list,tuple,str)
>>> L = list(range(100))
# 前10个数:
>>> L[:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 后10个数:
>>> L[-10:]
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
# 前11-20个数:
>>> L[10:20]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
# 前10个数,每两个取一个:
>>> L[:10:2]
[0, 2, 4, 6, 8]
# 所有数,每5个取一个:
>>> L[::5]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
二、迭代(Iterable)
Python中,只要是可迭代对象就可以迭代,而不关心具体是什么类型的数据。
判断是否可迭代
>>> from collections import Iterable
>>> isinstance('abc', Iterable) # str是否可迭代
True
>>> isinstance([1,2,3], Iterable) # list是否可迭代
True
>>> isinstance(123, Iterable) # 整数是否可迭代
False
dict 迭代
# 迭代key
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> for key in d:
# 迭代value
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> for value in d.values():
# 迭代key和value(荐)
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> for k, v in d.items():
下标enumerate
如果想实现for(int i=0; i<10; i++)的效果,可以使用enumerate
>>> for i, value in enumerate(['A', 'B', 'C']):
... print(i, value)
...
0 A
1 B
2 C
三、列表生成式
# 生成[1x1, 2x2, 3x3, ..., 10x10]
[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']
四、生成器(generator)
生成器:不会初始化所有数据而占用大量空间,而是根据规则计算下一个值。比如数据库的自增id
第一种方法
只要把一个列表生成式的[]改成()
>>> 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))
>>> g
<generator object <genexpr> at 0x1022ef630>
循环生成器
想获得下一个生成器的值可以用next()方法
但更好的方式是使用迭代器
>>> g = (x * x for x in range(10))
>>> for n in g:
... print(n)
...
0
1
4
9
16
25
36
49
64
81
第二种方法 yield关键字
举例:id自增(步长1)
def my_id():
id = 1
while True:
print(id)
id = id + 1
把print(id)换成yield id,这个方法就变成了生成器,方法不会一次性把所有id输出,而是每次输出yield的下一个值
def my_id():
id = 1
while id<10:
yield id
id = id + 1
>>> idd = my_id()
>>> next(idd)
1
>>> next(idd)
2
>>> next(idd)
3
>>> next(idd)
4
>>> next(idd)
5
>>> next(idd)
6
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 "<stdin>", line 1, in <module>
StopIteration
五、迭代器 (iterator)
可以直接作用于for循环的对象统称为可迭代对象:Iterable
可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator
判断迭代器与可迭代
>>> from collections import Iterable
# 是否可迭代的
>>> isinstance([], Iterable)
True
# 是否是迭代器
>>> from collections import Iterator
>>> isinstance((x for x in range(10)), Iterator)
True
把list、dict、str等Iterable变成Iterator可以使用iter()函数
>>> isinstance(iter([]), Iterator)
True
网友评论