Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

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))

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='
')

NOTE: I said earlier that ' '.join would be a good idea. That is only true for a list of str's.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...