简体   繁体   English

根据python中for循环内的函数返回的值创建一个列表

[英]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. 谷歌搜索没有产生任何相关性,这里唯一涉及同一问题的帖子是关于C,而不是Python。

Here's the situation: 情况如下:

I have a function with a for loop going through a range. 我有一个带有for循环的函数。 The for loop calls ANOTHER function which returns a different value each time the for loop runs. for循环调用ANOTHER函数,每次for循环运行时返回一个不同的值。 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). 我想要做的是将for循环调用的函数返回的所有值放入一个列表中(最终目的是获取列表中的最小值,我知道该怎么做)。

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 编辑:我应该提到这与uni分配有关,我只允许使用规范中定义的函数和参数

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. 编辑:@Michal,是的,我应该尝试自己解决它,我知道如何做你提到的所有事情,但我因为无法添加/修改函数参数而陷入困境。

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 . 基本上, for关键字之前的表达式将针对i每个值进行评估。 The square brackets surrounding this comprehension will save the results in a list, which you can call min() on it later. 围绕此理解的方括号将结果保存在列表中,您可以稍后在其上调用min()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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