returns 列表中的偶数并将它们减半的函数

Function that returns even numbers from a list and halves them

所以我在连接这个时遇到了问题,我不允许使用 .append(),现在我收到错误 'int' object not iterable.

def halveEvens(l):
    num = []
    for n in l:
        if n % 2 == 0:
            num += (n // 2)
        return num



print(halveEvens([10,21,32,42,55]))```

sum(x//2 for x in numbers if x%2 == 0)

我可能会这样做

如果你只是想收集它们(而不求和)

生成器 (x//2 for x in numbers if x%2 == 0) 将在您对其进行迭代时进行评估

或立即评估的列表理解 [x//2 for x in numbers if x%2 == 0]