1.all() 函数是判断可迭代对象中是否所有元素的值都为真;
any() 函数则是判断可迭代对象中是否存在某个元素的值为真。
2.enumerate()----每个元素及从 0 开始的序号共同构成一个二元组的列表
>>> seasons = ["Spring", "Summer", "Fall", "Winter"]
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
3.zip() -----用于创建一个聚合多个可迭代对象的迭代器。
>>> 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)]
4. map()-----根据提供的函数对可迭代对象的每个元素进行运算,并将返回运算结果的迭代器
如果可迭代对象的长度不一致,map()跟 zip() 函数一样,都是在最短的可迭代对象终止时结束
>>> 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]
5.filter()----根据提供的函数,对指定的可迭代对象的每个元素进行运算,并将运算结果为真的元素,以迭代器的形式返回。(看不懂)
>>> filter(str.islower, "FishC")
<filter object at 0x000001B5170FEFA0>
6.可迭代对象和迭代器----可迭代对象咱们可以对其进行重复的操作,而迭代器则是一次性的
课后:
1.请使用学过的知识,自己动手编写代码,利用 for 循环语句,模拟 all()、any()、enumerate()、zip() 这4个函数的实现。
x=[1,2,0]
for each in x:
if each:
print("True")
break
else:
print("False")
seasons=["spring","summer","fall","winter"]
result=[]
i=0
for each in seasons:
result.append((i,each))
i+=1
print(result)
x=[1,2,3]
y="shiloh"
if len(x)<len(y):
z=len(x)
else:
z=len(y)
result=[]
for i in range(z):
result.append((x[i],y[i]))
print(result)
2. 假设有一个密室,每次只能放一个人进去,在进去之前和出来之后都要求摁一下门口的打卡机按钮,编写代码,统计给定的数据,打印耗时最长和最短的人员名称。
times=[1,3,3.5,6.5,9.5,10,10.8]
names=["A", "B", "C", "D", "E", "F", "G"]
max_name=[names[0]]
min_name=[names[0]]
max_time=times[0]
min_time=times[0]
for i in range(1,len(names)):
each_name=names[i]
each_time=times[i]-times[i-1]
if each_time>max_time:
max_name.clear()
max_name.append(each_name)
max_time=each_time
elif each_time==max_time:
max_name.append(each_name)
elif each_time<min_time:
min_name.clear()
min_name.append(each_name)
min_time=each_time
elif each_time==min_time:
min_name.append(each_name)
print(f"速度最快的是:{min_name},耗费时间是:{min_time}")
print(f"速度最慢的是:{max_name},耗费时间是:{max_time}")