简体   繁体   中英

making a list from values returned by a function inside a for-loop in python

The reason I decided to sign up and ask about this is because it's quite a complicated and specific question (as you can probably tell from the title of this post, lol!). Googling didn't yield anything relevant, and the only post on here that dealt with the same issue was about C, not Python.

Here's the situation:

I have a function with a for loop going through a range. The for loop calls ANOTHER function which returns a different value each time the for loop runs. What I want to do is put all of those values returned by the function called by the for loop, into a list (the end aim is to get the minimum value in the list, which I know how to do).

I'm only a begginner programmer and I have no idea how to do this. It may be quite simple, but I can't get my head around it!

EDIT: I should have mentioned this is related to a uni assignment and I'm only allowed to use the functions and parameters defined in the specs

EDIT: @Michal, yes I should try to solve it myself and I know how to do all the things you've mentioned, but I'm stuck because of not being able to add/modify parameters to functions.

UPDATE: Problem solved! As I expected, it was something incredibly simple that I, being a bit of an idiot, didn't think of. Thanks to everyone who tried to help, I probably wouldn't have been able to figure it out without you.

You can do that with comprehension in one line.

l = [another_function(i) for i in range(lower, upper)]

Essentially, the expression right before the for keyword will get evaluated for each value of i . The square brackets surrounding this comprehension will save the results in a list, which you can call min() on it later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM