(python)将数组传递到函数中,条件用于数组中的每个

2024-03-29 10:47:39 发布

您现在位置: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()。我想要的是将每个值输入到函数中,遍历条件,并创建一个新数组,该数组保存来自my_函数(称为B)的return A。我该怎么做


1条回答
网友
1楼 · 发布于 2024-03-29 10:47:39

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

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函数

相关问题 更多 >