马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?注册
×
本帖最后由 15271953841 于 2024-2-22 05:57 编辑
Python 3.12.1 (tags/v3.12.1:2305ca5, Dec 7 2023, 22:03:25) [MSC v.1937 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
一、all() & any()
all() 函数判断可迭代对象中是否所有元素的值都为真,any() 函数则是判断可迭代对象中是否存在某个元素的值为真。
x=[1,1,0]
y=[1,1,9]
all(x)
False
all(y)
True
any(x)
True
any(y)
True
二、enumerate() 函数用于返回一个枚举对象,它的功能就是将可迭代对象中的每个元素及从0开始的序号共同构成一个二元组组的列表。
seasons=["Spring","Summer","Fall","Winter"]
enumerate(seasons)
<enumerate object at 0x0000029491903970> (创建一个枚举对象)
list(enumerate(seasons)) (查看它长的啥样,通过一个列表把它转化出来)
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
它将seasons这个列表的每个元素抽取出来,然后跟一个从0开始的索引去构成一个元组。
list 它还有一个start参数,可以自定义序号开始的值。
list(enumerate(seasons,10))
[(10, 'Spring'), (11, 'Summer'), (12, 'Fall'), (13, 'Winter')]
三、zip() 函数用于创建一个聚合多个可迭代对象的迭代器。它会将作为参数传入的每一个可迭代对象的每个元素依次组合成元组,即第i个元组包含来自每个参数的第i个元素。
x=[1,2,3]
y=[4,5,6]
zipped=zip(x,y) (zip就像拉链一样,把它们拉到一块)
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')]
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]
list(map(max,[1,3,5],[2,2,2],[0,3,9,8]))
[2, 3, 9]
五、filter() 函数会根据提供的函数对指定的可迭代对象的每一个元素进行运算,并将运算结果为真的元素,以迭代器的形式返回。
list(filter(str.islower,"FishC")) (filter就是过滤器)
['i', 's', 'h']
迭代器 VS 可迭代对象
一个迭代器肯定是一个可迭代对象。
区别:可迭代对象可以重复使用,
而迭代器则是一次性的。
mapped=map(ord,"FishC")
for each in mapped:
print(each)
70
105
115
104
67
list(mapped)
[]
可迭代对象可以重复使用,而迭代器只能搞一次,它是一次性的,所以我们看到一些函数,我们得看文档,看它返回的是一个可迭代对象,还是返回的一个迭代器。
x=[1,2,3,4,5]
y=iter(x)
type(x)
<class 'list'> (x是列表类型)
type(y)
<class 'list_iterator'> (y是一个列表的迭代器)
next(y) (逐个将迭代器中的元素提取出来)
1
next(y)
2
next(y)
3
next(y)
4
next(y)
5
next(y)
Traceback (most recent call last):
File "<pyshell#44>", 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,"没啦,被你掏空了~")
'没啦,被你掏空了~'
|