|
|
发表于 2023-2-21 23:38:22
|
显示全部楼层
《零基础入门学习Python》
(最新版)
小甲鱼 著
立即购买
判断真假值
all() 函数是判断可迭代对象中是否所有元素的值都为真;
any() 函数则是判断可迭代对象中是否存在某个元素的值为真。
>>> x = [1, 1, 0]
>>> y = [1, 1, 9]
>>> all(x)
False
>>> all(y)
Ture
>>> any(x)
True
>>> any(y)
True
枚举对象 ->将可迭代对象中的每个元素及从 0 开始的序号共同构成一个二元组的列表
enumerate() 函数用于返回一个枚举对象,它的功能就是将可迭代对象中的每个元素及从 0 开始的序号共同构成一个二元组的列表:
>>> seasons = ["Spring", "Summer", "Fall", "Winter"]
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
start 参数 自定义序号开始的值
>>> for i, j in enumerate(seasons, start=10):
... print(i, "->", j)
...
10 -> Spring
11 -> Summer
12 -> Fall
13 -> Winter
zip() 创建一个聚合多个可迭代对象的迭代器
做法是将作为参数传入的每个可迭代对象的每个元素依次组合成元组,即第 i 个元组包含来自每个参数的第 i 个元素。
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> z = [7, 8, 9]
>>> zipped = zip(x, y, z)
>>> list(zipped)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
传入的可迭代对象长度不一致,那么将会以最短的那个为准
>>> z = "FishC"
>>> zipped = zip(x, y, z)
>>> list(zipped)
[(1, 4, 'F'), (2, 5, 'i'), (3, 6, 's')]
itertools 模块与 zip_longest() 函数 保留多余的值
>>> import itertools
>>> zipped = itertools.zip_longest(x, y, z)
>>> list(zipped)
[(1, 4, 'F'), (2, 5, 'i'), (3, 6, 's'), (None, None, 'h'), (None, None, 'C')]
map() 函数 根据提供的函数对指定的可迭代对象的每个元素进行运算,并将返回运算结果的迭代器
>>> mapped = map(ord, "FishC")
>>> list(mapped)
[70, 105, 115, 104, 67]
指定的函数需要两个参数,可迭代对象的数量也应该是两个
>>> mapped = map(pow, [2, 3, 10], [5, 2, 3]))
>>> list(mapped)
[32, 9, 1000]
上面代码其实就相当于是:
>>> [pow(2, 5), pow(3, 2), pow(10, 3)]
[32, 9, 1000]
可迭代对象的长度不一致,那么 Python 采取的做法跟 zip() 函数一样,都是在最短的可迭代对象终止时结束
>>> list(map(max, [1, 3, 5], [2, 2, 2], [0, 3, 9, 8]))
[2, 3, 9] ##这里对比的是三个列表中每一个下标索引的最大值,而8这个长度其余没有,所以就不计入最大值
filter() 函数
>>> filter(str.islower, "FishC")
<filter object at 0x000001B5170FEFA0>
>>> list(filter(None, [True, False, 1, 0]))
[True, 1]
可迭代对象和迭代器
iter() 函数 将可迭代对象转换为迭代器
>>> x = [1, 2, 3, 4, 5]
>>> y = iter(x)
next() 函数 逐个将迭代器中的元素提取出来,一直到没有元素报错
>>> next(y)
1
>>> next(y)
2
>>> next(y)
3
>>> next(y)
4
>>> next(y)
5
>>> next(y)
Traceback (most recent call last):
File "<pyshell#52>", line 1, in <module>
next(y)
StopIteration
现在如果不想它抛出异常,那么可以给它传入第二个参数:
>>> z = iter(x)
>>> next(z, "没啦,被你掏空啦~")
1
>>> next(z, "没啦,被你掏空啦~")
2
>>> next(z, "没啦,被你掏空啦~")
3
>>> next(z, "没啦,被你掏空啦~")
4
>>> next(z, "没啦,被你掏空啦~")
5
>>> next(z, "没啦,被你掏空啦~")
'没啦,被你掏空啦~' |
|