编写将自然数列表转换为布尔值列表的Python函数:需求及代码咨询
Fixing and Optimizing Your Even/Odd Boolean List Function
First, let's break down the issues in your current code:
- Missing return statement: Your function builds
new_listbut doesn't return it, so callingprint(my_int_list(my_list))outputsNoneinstead of the expected boolean list. - Shadowing the built-in
listtype: Usinglistas a parameter name overwrites Python's nativelistclass—this is bad practice and can cause unexpected errors later. - Redundant
elifclause: Every integer is either even or odd, so checkingnum % 2 != 0in anelifis unnecessary; a simpleelseworks perfectly. - Unnecessary variable reassignment: You don't need to set
num = True/False—you can directly append the boolean result to your list.
Corrected Version of Your Original Loop Approach
Here’s how to fix those issues while keeping your initial loop structure:
def even_odd_booleans(numbers): new_list = [] for num in numbers: if num % 2 == 0: new_list.append(True) else: new_list.append(False) return new_list my_list = [2, 5, 8] print(even_odd_booleans(my_list)) # Output: [True, False, True]
More Pythonic & Optimized Implementation
Python’s list comprehensions are ideal for this kind of simple transformation—they’re concise, readable, and often faster than explicit loops for such tasks. Here’s the streamlined version:
def even_odd_booleans(numbers): return [num % 2 == 0 for num in numbers] my_list = [2, 5, 8] print(even_odd_booleans(my_list)) # Output: [True, False, True]
This works because num % 2 == 0 directly evaluates to a boolean (True for even numbers, False for odds), and we generate a list of these results in one line.
Quick Notes
- I renamed the function to
even_odd_booleansto make its purpose clearer, and the parameter tonumbersto avoid shadowing the built-inlist. - This assumes all inputs are valid natural numbers as specified. If you need to handle non-integer or non-positive inputs, you could add validation checks, but that’s beyond your original requirement.
内容的提问来源于stack exchange,提问作者George A
相关产品推荐
相关产品推荐

