python - 如何在将过滤值保持为零的同时过滤 Python 列表

标签 python list

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/

相关文章:

Python - 同时运行两个命令

python - 列表索引必须是整数,而不是str错误

python - 将两个列表,一个作为键,一个作为值,合并到 Python 中的字典中

python - 在mac 10.8.3上安装lxml

python - python中与*和+相关的正则表达式

python - 无法导入 pprint

Python:比较具有相似名称的文件(递归)

list - Ocaml 将 bool 列表评估为单个 bool 值

python - 如何跟踪链表以确定结果列表?

java - 为什么 CopyOnWriteLinkedList 不存在?