python - (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 A
from my_function 的新数组(称为 B)。我怎样才能做到这一点?
解决方案
您可以使用基本循环将您的函数映射到所需的序列上,在每次迭代中,循环将使用所需的值填充输出,如下所示:
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
函数。
推荐阅读
- blockchain - 从 r3 corda 应用程序从 v4.3 逐步升级到 4.4
- javascript - 执行块后捕获 Firebase 创建用户错误
- kubernetes - 为什么我的 MongoDB 部署会破坏 minikube(E0413,空 IP)?
- elasticsearch - 如何使用除“_id”之外的任何其他键批量更新弹性搜索文档?
- android - 如何自定义 Android BLE(蓝牙低功耗)gatt 传输速度?
- confluence - confluence wiki API 删除附件
- c++ - 从 string 到 const wchar_t* 的类型转换。类型不匹配
- java - Spring @Component 创建顺序
- reactjs - 在客户端和服务器之间共享 GraphQL 模式
- mysql - 如何避免 MySQL 中 where 子句中的语句重复?