好的,既然 filtered_results 已经按照 avg_profit (索引为 2 的元素) 降序排列,那么所有具有最高 avg_profit 的组合都会排在列表的最前面。
你可以通过以下几种方法来筛选出所有并列第一的组合:
方法一:使用循环和判断 (利用已排序的优势)
这是最直观的方法,利用列表已排序的特点,找到第一个元素的 avg_profit,然后收集所有 avg_profit 与之相等的元素。一旦遇到 avg_profit 不同的元素,就可以停止循环。
# 假设 filtered_results 已经按 avg_profit 降序排序
# filtered_results.sort(key=lambda x: x[2], reverse=True)
best_combinations = []
if filtered_results: # 检查列表是否为空
# 获取最高的平均收益
highest_avg_profit = filtered_results[0][2]
# 遍历列表,收集所有收益等于最高收益的组合
for result in filtered_results:
if result[2] == highest_avg_profit:
best_combinations.append(result)
else:
# 因为列表已排序,一旦遇到更小的收益,后面的肯定也更小,可以提前结束
break
else:
print("结果列表为空。")
# 现在 best_combinations 包含了所有并列第一的组合
# 你可以打印出来看看
print(f"找到 {len(best_combinations)} 个并列最佳组合:")
for combo in best_combinations:
print(combo)
# 如果你仍然需要选"一个"最佳组合(例如,用于后续步骤),
# 你可以从中任选一个,或者根据其他次要标准再筛选
# 例如,选择第一个找到的:
if best_combinations:
best_tp, best_sl, best_avg_profit, result_train, result_val, test_result = best_combinations[0]
print("\n选取的第一个最佳组合:", best_combinations[0])
方法二:使用列表推导式 (List Comprehension)
这种方法更简洁,但会遍历整个列表(不像方法一可以提前停止)。对于大多数情况,性能差异不大。
# 假设 filtered_results 已经按 avg_profit 降序排序
# filtered_results.sort(key=lambda x: x[2], reverse=True)
best_combinations = []
if filtered_results: # 检查列表是否为空
highest_avg_profit = filtered_results[0][2]
best_combinations = [result for result in filtered_results if result[2] == highest_avg_profit]
else:
print("结果列表为空。")
# 打印结果
print(f"找到 {len(best_combinations)} 个并列最佳组合:")
for combo in best_combinations:
print(combo)
# 同样,如果需要选一个
if best_combinations:
best_tp, best_sl, best_avg_profit, result_train, result_val, test_result = best_combinations[0]
print("\n选取的第一个最佳组合:", best_combinations[0])
方法三:使用 itertools.takewhile
这种方法结合了方法一的效率和类似列表推导式的简洁性。takewhile 会从迭代器的开头获取元素,直到某个元素的条件不再满足为止。
from itertools import takewhile
# 假设 filtered_results 已经按 avg_profit 降序排序
# filtered_results.sort(key=lambda x: x[2], reverse=True)
best_combinations = []
if filtered_results: # 检查列表是否为空
highest_avg_profit = filtered_results[0][2]
# 定义条件:元素的 avg_profit 等于最高的 avg_profit
condition = lambda x: x[2] == highest_avg_profit
# 使用 takewhile 获取所有满足条件的元素,并转换为列表
best_combinations = list(takewhile(condition, filtered_results))
else:
print("结果列表为空。")
# 打印结果
print(f"找到 {len(best_combinations)} 个并列最佳组合:")
for combo in best_combinations:
print(combo)
# 同样,如果需要选一个
if best_combinations:
best_tp, best_sl, best_avg_profit, result_train, result_val, test_result = best_combinations[0]
print("\n选取的第一个最佳组合:", best_combinations[0])
总结:
- 方法一 最直观,利用排序优势效率高。
- 方法二 代码简洁,但可能遍历整个列表。
- 方法三 结合了前两者的优点,既简洁又高效。
你可以根据自己的偏好和具体情况选择其中一种方法。核心思想都是先确定最高的 avg_profit 值,然后筛选出所有 avg_profit 等于该值的项。