温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python之并行遍历zip,遍历可迭代对象的内置函数map

发布时间:2020-09-06 15:27:18 来源:网络 阅读:997 作者:丁香花下 栏目:编程语言

                                Python之并行遍历zip,遍历可迭代对象的内置函数map,filter


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

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

● 基础语法:zip(*iterators)

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

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

'''
例如:
有两个列表
names = ['zhangsan','lisi','wangwu']
ages = [17,18,19]
zhangsan对应17 lisi对应18 wangwu对应19
同时遍历这两个列表
'''

# 1、使用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
'''

# 2、使用 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
'''


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

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

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

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

● 返回值: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')


三、遍历可迭代对象的内置函数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']


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI