Python中实现逐个提取浮点数组最小元素直至元素耗尽的方法
实现逐个取数组最小值并执行循环的方案
你可以根据数组是否会动态变动选择以下两种实现方式:
方案1:预先排序(适用于固定数组,效率更高)
先对数组做升序排序,直接按顺序遍历取值即可,完整代码如下:
import pandas as pd import numpy as np # 初始化参数 a = np.array([1.8, 1.2, 2.2, 1.6]) fin_SOC = 3.2 # 此处替换为你实际的pandas时间序列数据框 output_params = pd.DataFrame() # 数组升序排序后直接按顺序遍历,就是逐个取最小值的效果 sorted_a = np.sort(a) for int_SOC in sorted_a: i = 0 # 保留你原有逻辑执行while循环 while True: if int_SOC < fin_SOC: int_SOC += output_params.iloc[i, 3] else: break i += 1 print(int_SOC)
方案2:动态取数(适用于数组会动态新增/修改元素的场景)
每次循环取当前数组的最小值,使用后移除该值,直到数组为空,完整代码如下:
import pandas as pd import numpy as np a = np.array([1.8, 1.2, 2.2, 1.6]) fin_SOC = 3.2 # 此处替换为你实际的pandas时间序列数据框 output_params = pd.DataFrame() while a.size > 0: # 取当前数组最小值 min_idx = a.argmin() int_SOC = a[min_idx] # 从数组中移除已使用的最小值 a = np.delete(a, min_idx) # 执行你原有逻辑的while循环 i = 0 while True: # 建议补充i < len(output_params)的边界判断,避免索引越界 if int_SOC < fin_SOC and i < len(output_params): int_SOC += output_params.iloc[i, 3] else: break i += 1 print(int_SOC)
内容的提问来源于stack exchange,提问作者Nick
相关产品推荐
相关产品推荐

