Python从列表中选择最接近零的负值和正值

2024-10-05 10:38:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有很多清单。每个列表包含三个浮动。我需要从每个列表中选择一个最接近零的负值和正值。 以下是一个例子:

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() 

我不知道如何开始


Tags: 列表ifnpabspointoplist2list1
2条回答
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

求小于零的最大数和大于零的最小数

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

相关问题 更多 >

    热门问题