使用随机参数调用函数列表

2024-04-16 06:28:21 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用随机参数调用一组函数。你知道吗

import random

def sum_3 (a):
    return (sum(a) + 3)
def sum_2 (b):
    return (sum(b) + 2)

# Call the functions 
functions = [sum_3, sum_2]
# Using random arguments
random.sample(range(1, 100000), 5)

Tags: thesample函数import参数returndefrange
3条回答

您可以迭代函数并用示例调用它们。你知道吗

>>> the_sample = random.sample(range(1, 100000), 5)
>>> the_sample
>>> [6163, 38513, 35085, 4876, 27506]
>>>
>>> for func in functions:
...:    print(func(the_sample))
...:    
112146
112145

建立结果列表:

>>> [func(the_sample) for func in functions]
>>> [112146, 112145]

取决于你想打多少次电话。一种方法如下:

import random

def sum_3 (a):
    print('calling sum3 with', a)
    return (sum(a) + 3)

def sum_2 (b):
    print('calling sum2 with', b)
    return (sum(b) + 2)

functions = [sum_3, sum_2]
for i in range(3): # call each function 3 times
    for func in functions:
        print(func(random.sample(range(1, 100000), random.randint(2, 6))))

输出

calling sum3 with [76385, 37776, 19464]
133628
calling sum2 with [21520, 97936, 44610]
164068
calling sum3 with [1184, 4786]
5973
calling sum2 with [2680, 36487, 24265, 39569, 18331]
121334
calling sum3 with [87777, 81241, 95238, 58267, 3434, 85015]
410975
calling sum2 with [5020, 68999, 50868, 17544]
142433

假设functions是函数列表:

import random
# Call your function like this:
random.choice(functions)(a)

如果您喜欢使用np.random.choice(我这样做是因为它更像是一个默认的数学库)

相关问题 更多 >