与
input = [0,0,5,9,0,4,10,3,0]
作为列表 我需要一个输出,它将是输入中的两个最大值,同时将其他列表元素设置为零。
output = [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]
关于python - 如何在将过滤值保持为零的同时过滤 Python 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57431422/