Python之並行遍歷zip,遍歷可迭代對象的內置函數map,filter

                                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']


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章