提问人:Vilander Naoroibam 提问时间:10/23/2023 最后编辑:Vilander Naoroibam 更新时间:10/23/2023 访问量:50
我想创建一个函数,该函数检查某个值的类似名称的数组并相应地返回值
I want to create a function which checks similarly named arrays for a certain value and correspondingly return values
问:
我想要一个函数,它可以在名称相似的数组中搜索一个数字,然后返回与找到它的特定数组相对应的特定值。
我编写了以下使用 if 和 elif 的代码:
bf0 = np.arange(38,75,1)
for i in range(1,5):
globals()["bf"+str(i)] = globals()["bf"+str(i-1)]+37
def func(x):
if x in bf0:
return "x is in bf0"
elif x in bf1:
return "x is in bf1"
elif x in bf2:
return "x is in bf2"
elif x in bf3:
return "x is in bf3"
elif x in bf4:
return "x is in bf4"
虽然这可行,但我有什么方法可以将代码简化为更少的不重复行?
答:
0赞
Aria Noorghorbani
10/23/2023
#1
import numpy as np
arrays = {}
for i in range(5):
array_name = "bf" + str(i)
start = 38 + i * 37
end = 75
arrays[array_name] = np.arange(start, end, 1)
def search_array(x):
for array_name, array in arrays.items():
if x in array:
return f"{x} is in {array_name}"
return f"{x} is not in any array"
result = search_array(45)
print(result)
评论
eval()