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

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

list - Is the Python map function a value-returning function?

I've been trying to work with the map function in Python, and I've been having a little bit of trouble with it. I can't tell which of these is the proper way to map function foo to the list bar:

map(foo, bar)

or

newBar = map(foo, bar)

I'm getting varied results from different websites. Which of these is the correct usage?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In Python 2, map() returns a list of return values of foo(...). If you don't care about the results and just want to run the elements of bar through foo, either of your examples will work.

In Python 3, map() returns an iterator that is evaluated lazily. Neither of your examples will actually run any elements of bar through foo yet. You will need to iterate over that iterator. The simplest way would be to convert it to a list:

list(map(foo, bar))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...