首页 > 解决方案 > (python)使用数组中的每个条件将数组传递给函数

问题描述

我正在努力将数组传递给具有条件的已定义函数。

def my_function(input):
    if input<=45:
        A=-(1/15)*input - 21

    else:
        A=(1/46)*(input-45) - 24
    return A
A = arange(1,30,1)
B = my_function(A)

我收到一条错误消息,提示我需要使用 a.all() 或 a.any()。我想要的是将每个值输入到函数中,通过条件,并创建一个包含return Afrom my_function 的新数组(称为 B)。我怎样才能做到这一点?

标签: pythonarraysfunction

解决方案


您可以使用基本循环将您的函数映射到所需的序列上,在每次迭代中,循环将使用所需的值填充输出,如下所示:

def my_function(input):
    ret = 0
    if input<=45:
        ret = -(1/15)*input - 21
    else:
        ret = (1/46)*(input-45) - 24
    return ret

result = [] # Will store the processed values here

for i in range(1,30):
    result.append(my_function(i))

# Now result is populated with needed values

请注意,我假设您拼错了range函数。


推荐阅读