- 示例
代码维护在GitLab: map_reduce_zip_demo.py
# -*- 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
- zip() 内建函数无需导入
- zip()与izip()功能用法相同
- 使用izip()代替zip()在处理长列表时会获得更好性能, python2中需导入模块,python3中直接使用zip()
from itertools import izip as zip
# python2中需导入izip模块 - 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
- zip() 内建函数无需导入
- zip()与izip()功能用法相同
- izip()同py2中zip()
- 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