python - 如何过滤 Python 列表同时保持过滤值为零
问题描述
和
输入 = [0,0,5,9,0,4,10,3,0]
作为列表,我需要一个输出,这将是输入中的两个最高值,同时将其他列表元素设置为零。
输出 = [0,0,0,9,0,0,10,0,0]
我得到的最接近的:
from itertools import compress
import numpy as np
import operator
input= [0,0,5,9,0,4,10,3,0]
top_2_idx = np.argsort(test)[-2:]
test[top_2_idx[0]]
test[top_2_idx[1]]
你能帮忙吗?
解决方案
您可以排序,找到两个最大值,然后使用列表推导:
input = [0,0,5,9,0,4,10,3,0]
*_, c1, c2 = sorted(input)
result = [0 if i not in {c1, c2} else i for i in input]
输出:
[0, 0, 0, 9, 0, 0, 10, 0, 0]
推荐阅读
- javascript - 无法从控制器中的 HTTP 方法获取回调
- forestadmin - 智能字段 OBJECT 类型
- awk - 如何避免用awk返回系统命令?
- vba - 在抓取维基百科 URL 时避免 Google IP 阻塞
- javascript - 我们如何检查在 sap ui5 中单击了哪些图块?根据点击的图块调用不同的方法是什么?
- ajax - 在 WordPress 中使用 ajax 动态填充选择
- php - 只有 64 张图片正在发送到服务器
- syntax - 如何从此语法中消除歧义(antlr4)
- javascript - Highcharts 多列的平均值
- javascript - 我的js游戏不断分配和释放内存