简体   繁体   English

Python使用不同的参数多次调用函数

[英]Python call a function many times with different arguments

I have a function that takes two arguments. 我有一个带有两个参数的函数。 I want to run the function for every possible combination of my inputs, and store each returned value. 我想为输入的每种可能的组合运行该函数,并存储每个返回的值。 For example: 例如:

def foo(a, b):
    return (a + b)

if __name__ == "__main__":
    a = np.array([1., 2., 3.])
    b = np.array([5., 6.])
    f1 = foo(a[0], b[0]) #6
    f2 = foo(a[0], b[1]) #7
    f3 = foo(a[1], b[0]) #etc
    f4 = foo(a[1], b[1])
    f5 = foo(a[2], b[0])
    f6 = foo(a[2], b[1])

How can I call f1 through f6 in a more elegant way, like a loop? 如何以更优雅的方式(如循环)调用f1至f6? It can't be a direct loop, because a and b have differing numbers of elements. 它不能是直接循环,因为a和b具有不同数量的元素。

itertools.product is the way to go in a Pythonic manner. itertools.product是采用Python方式的一种方式。 However, if you are looking for a more raw, basic way, you'll need two for loops, which is the basic property of a cross product. 但是,如果您正在寻找一种更原始​​的基本方法,则需要两个for循环,这是叉积的基本属性。

for i in a:
    for j in b:
        foo(i, j)

Edit: 编辑:

Example usages of itertools.product : itertools.product用法示例:

for i, j in itertools.product(a, b):
    foo(i, j)

for tup in itertools.product(a, b):
    foo(*tup)

I prefer the first one because tuple's elements can be used explicitly if needed. 我更喜欢第一个,因为如果需要,可以显式使用元组的元素。

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

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