You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何过滤Python列表:保留前两大值,其余元素设为0

Solution to Retain Only the Two Largest Values in a List

Let's fix up your code step by step to get the desired output. First, a couple of quick notes on your existing code: you used a variable name test which doesn't exist (your input is called input), and you weren't creating a new list to hold the result with zeros everywhere except the top two values.

Here's the corrected version using NumPy:

import numpy as np

input_list = [0, 0, 5, 9, 0, 4, 10, 3, 0]  # Renamed to avoid conflict with Python's built-in `input` function

# Get indices of the two largest elements
top_2_indices = np.argsort(input_list)[-2:]

# Create an output list filled with zeros
output_list = [0] * len(input_list)

# Set the positions of the top two values to their original values
for idx in top_2_indices:
    output_list[idx] = input_list[idx]

print(output_list)  # Output: [0, 0, 0, 9, 0, 0, 10, 0, 0]

Key improvements:

  • Renamed input to input_list to avoid overriding Python's built-in input() function (a common best practice).
  • Created an output list initialized with zeros, matching the length of the input list.
  • Loop through the top two indices and populate those positions with their original values from the input list.

If you prefer a pure Python approach without NumPy, here's an alternative that works just as well:

input_list = [0, 0, 5, 9, 0, 4, 10, 3, 0]

# Get the two largest unique values (adjust if you need to keep duplicates)
top_2_values = sorted(set(input_list), reverse=True)[:2]

# Build the output list by keeping only the top two values, others as 0
output_list = [x if x in top_2_values else 0 for x in input_list]

print(output_list)  # Same desired output

Note: If your list might have multiple instances of the top values (e.g., two 10s) and you want to keep all of them, replace the top_2_values line with:

sorted_vals = sorted(input_list, reverse=True)
top_2_values = sorted_vals[:2]

内容的提问来源于stack exchange,提问作者Dominik Novotný

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:45:59