我有很多列表。每个列表包含三个浮动。我需要从每个列表中选择一个最接近零的负数和正数。以下是示例:
list1= [-18.987536121749894, 9.154936510174036, -4.626424654409895]
list2= [-4.626424654409895, 9.154936510174036, 2.355498340416582]
list3= [-0.5, 0.1, 0.005]
我的预期输出:
list1_op= [-4.626424654409895, 9.154936510174036]
list2_op= [-4.626424654409895, 2.355498340416582]
list3_op= [-0.5, 0.005]
我的代码:
while loop:
...
...
pdif = fun(mf1,mf2,mf3) # mf1 and mf2 are extreme points, mf3 is middle point between them
asign = np.sign(pdif) # check for sign change in Pdif list
signchange = ((np.roll(asign, 1) - asign) != 0).astype(int)
print(pdif)
if abs(pdif[2])<0.01:
print("Optimal point reached")
break
else:
if signchange.sum()>0: # If yes then there is a merging point
if (pdif[2]<abs(pdif[0]))&(signchange[1]==1):
mf1 = mf3
elif (pdif[2]<abs(pdif[1]))&(signchange[2]==1):
mf2 = mf3
mf3 = np.array([mf1,mf2]).mean()
我不知道该怎么开始。
查找小于零的最大数和大于零的最小数。
import numpy as np
a = [-18.987536121749894, 9.154936510174036, -4.626424654409895]
b = [-4.626424654409895, 9.154936510174036, 2.355498340416582]
c = [-0.5, 0.1, 0.005]
for thing in (a,b,c):
thing = np.array(thing)
x = thing[thing<0].max()
y = thing[thing>0].min()
ix = np.where(np.isclose(thing,x))[0]
iy = np.where(np.isclose(thing,y))[0]
print(f'{x},{y},{ix},{iy}')
# or
indices = np.where(np.any(np.isclose(thing[:,None],[x,y]),axis=-1))
print(f'indices:{indices[0]}')
如果正在测试的列表中没有正数或负数,将抛出ValueError。
output_list = [None]*len(lists)
for i in len(lists):
list = lists[i]
smallest_positive = list[list>0].min()
biggest_negative = list[list<0].max()
output_list[i] = (smallest_positive, biggest_negative)
return output_list