包含方块的函数

问题描述 投票:0回答:1

我尝试解决以下挑战

sq_cube([50/2, 40/3, 30/4, 20/5, 10/6]) == [[64, 512], [16, 64], [4, 8]]

这是使用的代码,它以某种方式返回一个空白列表

[]
而不是
[[64, 512], [16, 64], [4, 8]]

def sq_cube(numbers):
    return [[round(num ** 2), round(num ** 3)] for num in numbers if num % 2 == 0]
python
1个回答
0
投票
def sq_cube(numbers):
    # Note  input [50 / 2, 40 / 3, 30 / 4, 20 / 5, 10 / 6]
    # becomes numbers = [25.0, 13.333333333333334, 7.5, 4.0, 1.6666666666666667]
    # only 4.0 is processed.
    print(numbers)
    return [[round(num ** 2), round(num ** 3)] for num in numbers if
            num % 2 == 0]


print(sq_cube([50 / 2, 40 / 3, 30 / 4, 20 / 5, 10 / 6]))


def sq_cube_a(numbers):
    """
    A version of the list comprehension expanded to demonstrate functionality.
    Step through the code with a debugger will make it visiable why the only
    value processed is 4.0 with an input  of
    [50 / 2, 40 / 3, 30 / 4, 20 / 5, 10 / 6]
    """

    # Note  input [50 / 2, 40 / 3, 30 / 4, 20 / 5, 10 / 6]
    # becomes numbers = [25.0, 13.333333333333334, 7.5, 4.0, 1.6666666666666667]
    # only 4.0 is processed.
    for num in numbers:
        if num % 2 == 0:
            # only 4.0 is processed.
            a = [round(num ** 2), round(num ** 3)]
            print(a)


print(sq_cube_a([50 / 2, 40 / 3, 30 / 4, 20 / 5, 10 / 6]))

输出

[25.0, 13.333333333333334, 7.5, 4.0, 1.6666666666666667]
[[16, 64]]
[16, 64]
None
© www.soinside.com 2019 - 2024. All rights reserved.