Python冷知识:方便的并行迭代工具----zip函数

迭代工具

  1. 并行迭代
    我们一般迭代是采用如下的代码,显得很笨拙。
names=['anne','beth','jack','peter']
ages=[12,34,23,15]
#如果要打印名字和对应的年龄,可以像下面这样做:
for i in range(len(names)):
    print(names[i],'is',ages[i],'years old')

anne is 12 years old
beth is 34 years old
jack is 23 years old
peter is 15 years old

这里有个很有用并行迭代工具,内置函数zip,它可以将两个序列“缝合”起来,返回一个由元组组成的序列。返回值是一个适合迭代的对象,要查看其内容,可使用list将其转换为列表

names=['anne','beth','jack','peter']
ages=[12,34,23,15]
print(list(zip(names,ages)))

[('anne', 12), ('beth', 34), ('jack', 23), ('peter', 15)]

“缝合”后,可利用循环方法将元组里的元素进行解包。

for name,age in zip(names,ages):
    print(name,'is',age,'years old')
    
anne is 12 years old
beth is 34 years old
jack is 23 years old
peter is 15 years old

函数zip可用于缝合任意数量的序列。需要指出的是,当序列的长度不同时,函数zip将在最短的序列用完后停止“缝合”。

list(zip(range(5),range(1000)))

[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

猜你喜欢

转载自blog.csdn.net/qq_28766729/article/details/82752813