因此,如果变量高于第一个列表中的值但低于第二个列表中的值,则需要将变量设置为列表的索引。我有一个从0到360的值的flowDir。我试图将Direction变量设置为正确的索引
new_array1 = [22.5, 67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5]
new_array2 = [67.5, 112.5, 157.5, 202.5, 247.5,292.5, 337.5, 22.5]
for n in range(8):
array1 = new_array1[n]
array2 = new_array2[n]
if flowDir > array1 and flowDir < array2:
Direction = n
答案 0 :(得分:0)
由于角度是有序的,您可以使用bisect.bisect_left()
:
import bisect
angles = [22.5, 67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5]
flow_dir = 100
print(bisect.bisect_left(angles, flow_dir ) - 1)
答案 1 :(得分:0)
numpy.digitize也使用二进制搜索
import numpy as np
bins = [22.5, 67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5]
flow_dir = 100
int(np.digitize(flow_dir, bins)) - 1
Out[21]: 1
你可以给它一个dirs的列表(或数组)
flow_dirs = [100, 210, 50, 300]
np.digitize(flow_dirs, bins) - 1
Out[23]: array([1, 4, 0, 6], dtype=int64)