python 3.6.3版函数和列表

2024-05-04 21:59:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试运行以下命令:

def count_small(numbers):
total = 0
for n in numbers:
    if n < 10:
        total = total + 1
    return total

lotto = [4, 8, 15, 16, 23, 42]
small = count_small(lotto)
print(small)

在这里我定义了一个函数'count\u small(numbers)' 从0开始, 然后检查列表中的每一项,以检查它是否小于10,如果该项小于10,则总数将加1。我正在运行列表“lotto”上的函数,因为您可以看到“lotto”有两个小于10的数字“4”和“8”,因此它应该返回2,但是,当我运行代码时,它返回1。你知道吗


Tags: 函数in命令列表forreturnif定义
2条回答

你的缩进不正确。将return语句放在for循环之外。你知道吗

您的return语句位于for循环内,因此函数位于第一个数字之后。你知道吗

def count_small(numbers):
    total = 0
    for n in numbers:
        if n < 10:
            total += 1
    return total

使用生成器表达式时,可以将其写入一行:

def count_small(numbers):
    return sum(n<10 for n in numbers)

相关问题 更多 >