简体   繁体   English

Python:如何使用一系列参数重复调用函数?

[英]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次,每次以foox参数为大(从1开始),直到它以barx参数运行。 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 . 由于应运行的次数不同,并且该数字可能成千上万,因此为介于1x之间的每个数字编写略有变化的代码行是不切实际的。

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.

相关问题 如何使用AWS开发工具包从YAML文件到Python重复调用带有成对参数列表的函数? - how to repeatedly call a function with a list of paired arguments from YAML file to Python using AWS SDK? 如何重复将参数传递给python文件 - How to repeatedly pass arguments to a python file 如何避免 Python 中 function 调用中重复 arguments - How to avoid repeated arguments in function call in Python 3 如何重复调用一个函数? - How do I call a function repeatedly? Python 3:如何从另一个文件调用函数并将参数传递给该函数? - Python 3: How to call function from another file and pass arguments to that function ? 如何调用 function 和 arguments 在 ZA7F5F35426B9237411FCZ2317B 中使用另一个 function - How to call a function with arguments using another function in Python Python函数调用中的条件参数 - Conditional arguments in Python function call Python:用 n arguments 调用 function - Python : call a function with n arguments Python GUI 重复调用 function 并按下按钮 - Python GUI call function repeatedly and have button Presses 在函数中使用可选参数来反转范围 python 3 - Using optional arguments in a function to reverse a range python 3
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM