如何用Python正确提取列表中大于m且小于n的元素?
Fixing Your Python Code for Filtering List Elements
Hey there! Let's walk through the issues in your code and get it working correctly for your requirement.
Key Issues in the Original Code
- Syntax Error in Boolean Indexing: The line
final_array =array_1[array_1>m array_1<n]is missing a logical operator. For numpy array boolean indexing, you need to use&(logical AND) to combine conditions, and wrap each condition in parentheses (due to operator precedence rules). - Output Format Mismatch: Your code returns a numpy array, but the example expects a standard Python list. You'll need to convert the numpy result to a list.
- Unnecessary Dependency: While numpy works, this task can be achieved more simply with native Python, no external libraries required.
Corrected Version Using Numpy
If you want to stick with numpy, here's the fixed code:
import ast import numpy as np # Move imports to the top for better code structure input_list = ast.literal_eval(input()) m = int(input()) n = int(input()) array_1 = np.array(input_list) # Fix the boolean indexing with proper operator and parentheses final_array = array_1[(array_1 > m) & (array_1 < n)] # Convert numpy array to Python list to match the example output format print(final_array.tolist())
Simpler Native Python Implementation (Recommended)
This approach avoids numpy entirely and uses a list comprehension, which is more lightweight and readable for this task:
import ast input_list = ast.literal_eval(input()) m = int(input()) n = int(input()) # List comprehension to filter elements between m and n final_list = [num for num in input_list if m < num < n] print(final_list)
Test with Example Input
Example Input:
Enter the array:[1, 5, 9, 12, 15, 7, 12, 9]
Enter m:6
Enter n:12
Both versions will output: [9, 7, 9], which matches the expected result perfectly.
内容的提问来源于stack exchange,提问作者Tejas Jadhao
相关产品推荐
相关产品推荐

