[英]Python: How to call a function repeatedly with a range of arguments?
Let's say I have two functions. 假设我有两个功能。
One has two arguments, but one of them is a keyword arg, so it doesn't come up often. 一个有两个参数,但是其中一个是关键字arg,因此它不会经常出现。
def foo(x, _y=1):
print str(x)
The other has one argument. 另一个有一个论点。
def bar(x)
Ideally, It would run foo
x
times, each time with foo
's x
argument being one larger (starting at one), until it is ran with bar
's x
argument. 理想情况下,它将运行foo
x
次,每次以foo
的x
参数为大(从1开始),直到它以bar
的x
参数运行。 Due to the varying number of times it should be run, as well as the fact this number may potentially be in the thousands, it wouldn't be practical to make a slightly-varying line of code for every number between 1
and x
. 由于应运行的次数不同,并且该数字可能成千上万,因此为介于1
和x
之间的每个数字编写略有变化的代码行是不切实际的。
In other words, how would I make a function run multiple times, once for each number in range(1, x + 1)
? 换句话说,我如何使一个函数多次运行,一次对range(1, x + 1)
每个数字执行一次?
Never mind. 没关系。 As Ignacio Vazquez-Abrams helpfully points out, this could be done with a simple for
loop. 正如Ignacio Vazquez-Abrams指出的那样,可以使用简单的for
循环来完成此操作。
After all, with a simple little snippet such as: 毕竟,有一个简单的小片段,例如:
def bar(x):
for val in range(1, x + 1):
foo(val)
... we get our goal, for example: ...我们实现了目标,例如:
bar(5)
results in 结果是
foo(1)
foo(2)
foo(3)
foo(4)
foo(5)
(Thanks to tdelany for giving this clumsy novice a tip.) (感谢tdelany给这个笨拙的新手一个提示。)
...I really need to brush up on Python. ...我真的需要重温Python。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.