Python map/reduce/zip 內建函數使用

  • 示例
# -*- coding:utf-8 -*-
try:    # 做Python2的兼容
	from itertools import izip as zip   # izip比zip在處理大列表時更快
except Exception as e:
	print(e)
try:      # 做Python3的兼容
	from functools import reduce  # python3 需導入,python2 內建
except Exception as e:
	print(e)

name = ["張三", "李四", "王五", "李六"]  # 保存名字列表
sign = ["白羊座", "雙魚座", "獅子座", "處女座"]  # 保存星座列表

# zip & unzip
zipper = zip(name,sign)		#  輸出:> zip object, 可迭代對象
unzipper=zip(*zipper)		#  輸出:> zip object, 可迭代對象

# zip & dict
print(dict(zip(name, sign)))	# py3輸出:> {'張三': '白羊座', '李四': '雙魚座', '王五': '獅子座', '李六': '處女座'}
								# py2輸出:> {'\xe5\xbc\xa0\xe4\xb8\x89': '\xe7\x99\xbd\xe7\xbe\x8a\xe5\xba\xa7', '\xe6\x9d\x8e\xe5\x9b\x9b': '\xe5\x8f\x8c\xe9\xb1\xbc\xe5\xba\xa7', '\xe7\x8e\x8b\xe4\xba\x94': '\xe7\x8b\xae\xe5\xad\x90\xe5\xba\xa7', '\xe6\x9d\x8e\xe5\x85\xad': '\xe5\xa4\x84\xe5\xa5\xb3\xe5\xba\xa7'}

# 用map reduce 實現 zip & dict 功能
# map & reduce
mapper = map( lambda x,y: {x:y}, name, sign)	# 使用map函數,將兩個一維數組的元素分別組合成字典K-V
reducer = reduce( lambda x,y: dict(x, **y), list(mapper))  # 使用reduce函數,將所有字典元素聚合
print (reducer)				# py3輸出:> {'張三': '白羊座', '李四': '雙魚座', '王五': '獅子座', '李六': '處女座'}

1. zip函數使用

  • Python2

    1. zip() 內建函數無需導入
    2. zip()與izip()功能用法相同
    3. 使用izip()代替zip()在處理長列表時會獲得更好性能, python2中需導入模塊,python3中直接使用zip()

      from itertools import izip as zip # python2中需導入izip模塊

    4. zip(*_)爲解包
    """
    izip(iter1 [,iter2 [...]]) --> izip object
    
    Return a izip object whose .next() method returns a tuple where
    the i-th element comes from the i-th iterable argument.  The .next()
    method continues until the shortest iterable in the argument sequence
    is exhausted and then it raises StopIteration.  Works like the zip()
    function but consumes less memory by returning an iterator instead of
    a list.
    """
    
  • Python3

    1. zip() 內建函數無需導入
    2. zip()與izip()功能用法相同
    3. izip()同py2中zip()
    4. zip(*_)爲解包
    """
    zip(iter1 [,iter2 [...]]) --> zip object
    
    Return a zip object whose .__next__() method returns a tuple where
    the i-th element comes from the i-th iterable argument.  The .__next__()
    method continues until the shortest iterable in the argument sequence
    is exhausted and then it raises StopIteration.
    """
    

2. map() 函數使用

  • Python2/3都屬於內建函數
  • Python2/3中 map() 函數區別只有返回值不同

    ###Python2的導入
    map(function, sequence[, sequence, ...]) -> list
    ###Python3的導入
    map(func, *iterables) --> map object

3. reduce() 函數使用

  • Python2 reduce() 屬於內建模塊
  • Python3 reduce() 使用需導入模塊

    from functools import reduce

  • Python2/3 reduce() 函數使用完全相同

    reduce(function, sequence[, initial]) -> value

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