打印在地图中时不打印,Python [英] Print doesn't print when it's in map, Python
问题描述
primes = [2,3,5,7..] (prime numbers)
map(lambda x:print(x),primes)
它不打印任何东西.这是为什么?我试过了
It does not print anything. Why is that? I've tried
sys.stdout.write(x)
也是,但也不起作用.
推荐答案
由于 lambda x: print(x)
是 Python 中的语法错误3,我假设 Python 3.这意味着 map
返回一个生成器,这意味着要让 map 实际调用列表的每个元素上的函数,您需要遍历生成的生成器.
Since lambda x: print(x)
is a syntax error in Python < 3, I'm assuming Python 3. That means map
returns a generator, meaning to get map to actually call the function on every element of a list, you need to iterate through the resultant generator.
幸运的是,这很容易做到:
Fortunately, this can be done easily:
list(map(lambda x:print(x),primes))
哦,如果你愿意,你也可以去掉 lambda:
Oh, and you can get rid of the lambda too, if you like:
list(map(print,primes))
但是,在这一点上,您最好让 print 处理它:
But, at that point you are better off with letting print handle it:
print(*primes, sep='
')
<小时>
注意:我之前说过 '
'.join
是个好主意.这仅适用于 str 列表.
NOTE: I said earlier that '
'.join
would be a good idea. That is only true for a list of str's.
这篇关于打印在地图中时不打印,Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!