用
输入= [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]]
Run Code Online (Sandbox Code Playgroud)
你能帮忙吗?
您可以排序,找到两个最大值,然后使用列表推导:
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]
Run Code Online (Sandbox Code Playgroud)
输出:
[0, 0, 0, 9, 0, 0, 10, 0, 0]
Run Code Online (Sandbox Code Playgroud)
不像Ajax的解决方案那么漂亮,而是一个O(n)解决方案和更动态的内容:
from collections import deque
def zero_non_max(lst, keep_top_n):
"""
Returns a list with all numbers zeroed out
except the keep_top_n.
>>> zero_non_max([0, 0, 5, 9, 0, 4, 10, 3, 0], 3)
>>> [0, 0, 5, 9, 0, 0, 10, 0, 0]
"""
lst = lst.copy()
top_n = deque(maxlen=keep_top_n)
for index, x in enumerate(lst):
if len(top_n) < top_n.maxlen or x > top_n[-1][0]:
top_n.append((x, index))
lst[index] = 0
for val, index in top_n:
lst[index] = val
return lst
lst = [0, 0, 5, 9, 0, 4, 10, 3, 0]
print(zero_non_max(lst, 2))
Run Code Online (Sandbox Code Playgroud)
输出:
[0, 0, 0, 9, 0, 0, 10, 0, 0]
Run Code Online (Sandbox Code Playgroud)