2

What is a good pythonic way to generate an array of results from multiple function calls with a function that changes what it returns after each call? For example, say I have a function foo that returns 'callno-X' each time it is called, and X is increased by 1 every time. I want to then be able to say something like bar(5) that will call foo() five times and gather the results in an array, returning ['callno-1','callno-2','callno-3','callno-4','callno-5']. Is there any good way to do this?

4

2 回答 2

7

Just use a list comprehension:

returnValues = [foo() for x in xrange(5)]
于 2013-07-08T17:50:11.377 回答
1

How about this:

map(foo, xrange(5))

It's short and simple.

于 2013-07-08T18:00:06.780 回答