这篇文章给大家分享的是Python并行遍历zip和遍历可迭代对象map、filter函数的实现过程。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。

一、使用内置函数zip并行遍历

zip()的目的是映射多个容器的相似索引,以便它们可以仅作为单个实体使用。

●基础语法:zip(*iterators)

●参数:iterators为可迭代的对象,例如list,string

●返回值:返回单个迭代器对象,具有来自所有容器的映射值

'''例如:有两个列表names=['zhangsan','lisi','wangwu']ages=[17,18,19]zhangsan对应17lisi对应18wangwu对应19同时遍历这两个列表'''#1、使用forin循环可以实现names=['zhangsan','lisi','wangwu']ages=[17,18,19]foriinrange(3):print('nameis%s,ageis%i'%(names[i],ages[i]))'''nameiszhangsan,ageis17nameislisi,ageis18nameiswangwu,ageis19'''#2、使用zip进行并行遍历更方便forname,ageinzip(names,ages):print('nameis%s,ageis%i'%(name,age))'''nameiszhangsan,ageis17nameislisi,ageis18nameiswangwu,ageis19'''


二、遍历可迭代对象的内置函数map

map()函数的主要作用是可以把一个方法依次执行在一个可迭代的序列上,比如List等,具体的信息如下:

● 基础语法:map(fun, iterable)

● 参数:fun是map传递给定可迭代序列的每个元素的函数。iterable是一个可以迭代的序列,序列中的每一个元素都可以执行fun

● 返回值:map object

result=map(ord,'abcd')print(result)#<mapobjectat0x7f1c493fc0d0>print(list(result))#[97,98,99,100]result=map(str.upper,'abcd')print(tuple(result))#'A','B','C','D')


三、遍历可迭代对象的内置函数filter

filter()方法借助于一个函数来过滤给定的序列,该函数测试序列中的每个元素是否为真。

●基础语法:filter(fun, iterable)

●参数:fun测试iterable序列中的每个元素执行结果是否为True,iterable为被过滤的可迭代序列

●返回值:可迭代的序列,包含元素对于fun的执行结果都为True


result=filter(str.isalpha,'123abc')print(result)#<filterobjectat0x7fd47f2045d0>print(list(result))#['a','b','c']result=filter(str.isalnum,'123*(^&abc')print(list(result))#['1','2','3','a','b','c']#filter示例deffun(values):Internal_value=['i','o','b','c','d','y','n']ifvaluesinInternal_value:returnTrueelse:returnFalsetest_value=['i','L','o','v','e','p','y','t','h','o','n']result=list(filter(fun,test_value))print(result)#['i','o','y','o','n']

以上就是Python并行遍历zip和遍历可迭代对象map、filter函数的实现过程,看完之后是否有所收获呢?如果想了解更多相关内容,欢迎关注亿速云行业资讯!