如何过滤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
inputtoinput_listto avoid overriding Python's built-ininput()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ý
相关产品推荐
相关产品推荐

