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

编写将自然数列表转换为布尔值列表的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_list but doesn't return it, so calling print(my_int_list(my_list)) outputs None instead of the expected boolean list.
  • Shadowing the built-in list type: Using list as a parameter name overwrites Python's native list class—this is bad practice and can cause unexpected errors later.
  • Redundant elif clause: Every integer is either even or odd, so checking num % 2 != 0 in an elif is unnecessary; a simple else works 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_booleans to make its purpose clearer, and the parameter to numbers to avoid shadowing the built-in list.
  • 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 12:12:27