在地图中打印时不打印,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)
也可以,但是也不起作用.
too, but doesn't work either.
推荐答案
由于lambda x: print(x)
是Python中的语法错误< 3,我假设使用Python3.这意味着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))
但是,此时最好让打印处理它:
But, at that point you are better off with letting print handle it:
print(*primes, sep='\n')
注意:我之前说过'\n'.join
是个好主意.这仅适用于str的列表.
NOTE: I said earlier that '\n'.join
would be a good idea. That is only true for a list of str's.
这篇关于在地图中打印时不打印,Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!