Python之并行遍历zip,遍历可迭代对象的内置函数map,filterpython
1、使用内置函数zip并行遍历ide
zip()的目的是映射多个容器的类似索引,以便它们能够仅做为单个实体使用。函数
● 基础语法:zip(*iterators)测试
● 参数:iterators为可迭代的对象,例如list,stringspa
● 返回值:返回单个迭代器对象,具备来自全部容器的映射值对象
''' 例如: 有两个列表 names = ['zhangsan','lisi','wangwu'] ages = [17,18,19] zhangsan对应17 lisi对应18 wangwu对应19 同时遍历这两个列表 ''' # 一、使用for in 循环能够实现 names = ['zhangsan','lisi','wangwu'] ages = [17,18,19] for i in range(3): print('name is %s,age is %i' % (names[i],ages[i])) ''' name is zhangsan,age is 17 name is lisi,age is 18 name is wangwu,age is 19 ''' # 二、使用 zip进行并行遍历更方便 for name,age in zip(names,ages): print('name is %s,age is %i' % (name,age)) ''' name is zhangsan,age is 17 name is lisi,age is 18 name is wangwu,age is 19 '''
2、遍历可迭代对象的内置函数map索引
map()函数的主要做用是能够把一个方法依次执行在一个可迭代的序列上,好比List等,具体的信息以下:ip
● 基础语法:map(fun, iterable)string
● 参数:fun是map传递给定可迭代序列的每一个元素的函数。iterable是一个能够迭代的序列,序列中的每个元素均可以执行funit
● 返回值:map object
result = map(ord,'abcd') print(result) # <map object at 0x7f1c493fc0d0> print(list(result)) # [97, 98, 99, 100] result = map(str.upper,'abcd') print(tuple(result)) # 'A', 'B', 'C', 'D')
3、遍历可迭代对象的内置函数filter
filter()方法借助于一个函数来过滤给定的序列,该函数测试序列中的每一个元素是否为真。
● 基础语法:filter(fun, iterable)
● 参数:fun测试iterable序列中的每一个元素执行结果是否为True,iterable为被过滤的可迭代序列
● 返回值:可迭代的序列,包含元素对于fun的执行结果都为True
result = filter(str.isalpha,'123abc') print(result) # <filter object at 0x7fd47f2045d0> print(list(result)) # ['a', 'b', 'c'] result = filter(str.isalnum,'123*(^&abc') print(list(result)) # ['1', '2', '3', 'a', 'b', 'c'] # filter示例 def fun(values): Internal_value = ['i','o','b','c','d','y','n'] if values in Internal_value: return True else: return False test_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']