map a binary function over pairs of lists in Python 3
本问题已经有最佳答案,请猛点这里访问。
为什么我要进入Python2
1 2 | >>> map(max,[1,2],[3,1]) [3, 2] |
在Python 3中
1 2 | >>> map(max,[1,2],[3,1]) <map object at 0x10c2235f8> |
?
在python3中应该用什么替代
我读到在python3中应该使用列表理解,但是
1 2 | >>> [max(i,j) for i in [1,2] for j in [3,1]] [3, 1, 3, 2] |
并没有给出预期的结果,也没有想到的变化。
这是因为
来自PyDOC〔2〕:
If there are multiple arguments, map() returns a list consisting of
tuples containing the corresponding items from all iterables (a kind
of transpose operation). The iterable arguments may be a sequence or
any iterable object; the result is always a list.
而
来自PyDOC〔3〕:
Return an iterator that applies function to every item of iterable,
yielding the results.
所以要把
1 | list(map(...)) |
基本上:
1 2 | >>> list(map(max,[1,2],[3,1])) => [3, 2] |