首页 > 解决方案 > 如何过滤 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]]

你能帮忙吗?

标签: pythonlist

解决方案


您可以排序,找到两个最大值,然后使用列表推导:

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]

推荐阅读