问题描述
我有兴趣了解 新Python 3.x的语言设计.
我很喜欢 Python 2.7 中的函数 map
:
I do enjoy, in Python 2.7, the function map
:
Python 2.7.12
In[2]: map(lambda x: x+1, [1,2,3])
Out[2]: [2, 3, 4]
但是,在 Python 3.x 中,情况发生了变化:
However, in Python 3.x things have changed:
Python 3.5.1
In[2]: map(lambda x: x+1, [1,2,3])
Out[2]: <map at 0x4218390>
我明白怎么做,但我找不到原因的参考.为什么语言设计者会做出这样的选择,在我看来,这会带来很大的痛苦.这是为了让开发人员坚持列表理解吗?
I understand the how, but I could not find a reference to the why. Why did the language designers make this choice, which, in my opinion, introduces a great deal of pain. Was this to arm-wrestle developers in sticking to list comprehensions?
IMO,列表自然可以认为是 Functors;我一直被认为是这样思考的:
IMO, list can be naturally thought as Functors; and I have been somehow been thought to think in this way:
fmap :: (a -> b) -> f a -> f b
推荐答案
我认为当 根本dev/peps/pep-0289/" rel="noreferrer">生成器表达式 也存在,是它可以接受多个迭代器参数,这些参数都被循环并传递给函数:
I think the reason why map still exists at all when generator expressions also exist, is that it can take multiple iterator arguments that are all looped over and passed into the function:
>>> list(map(min, [1,2,3,4], [0,10,0,10]))
[0,2,0,4]
这比使用 zip 稍微容易一些:
That's slightly easier than using zip:
>>> list(min(x, y) for x, y in zip([1,2,3,4], [0,10,0,10]))
否则,它根本不会在生成器表达式上添加任何内容.
Otherwise, it simply doesn't add anything over generator expressions.
这篇关于为什么 map 在 Python 3 中返回一个地图对象而不是一个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!