使用列表理解打印奇数

Print the odd number using list comprehension

问题是:

The odd_numbers function returns a list of odd numbers between 1 and n, inclusively. Fill in the blanks in the function, using list comprehension. Hint: remember that list and range counters start at 0 and end at the limit minus 1.

def odd_numbers(n):
    return [x for x in ___ if ___]

print(odd_numbers(5))  # Should print [1, 3, 5]
print(odd_numbers(10)) # Should print [1, 3, 5, 7, 9]
print(odd_numbers(11)) # Should print [1, 3, 5, 7, 9, 11]
print(odd_numbers(1))  # Should print [1]
print(odd_numbers(-1)) # Should print []

这是我的代码:

def odd_numbers(n):
    return [x for x in range(0, n) if x%2 != 0]

print(odd_numbers(5))  # Should print [1, 3, 5]
print(odd_numbers(10)) # Should print [1, 3, 5, 7, 9]
print(odd_numbers(11)) # Should print [1, 3, 5, 7, 9, 11]
print(odd_numbers(1))  # Should print [1]
print(odd_numbers(-1)) # Should print []

我的代码输出为:

Here is your output: [1, 3] [1, 3, 5, 7, 9] [1, 3, 5, 7, 9] [] []

Not quite, odd_numbers(5) returned [1, 3] instead of [1, 3, 5]. Remember that list comprehensions let us use a conditional clause. What's the condition to determine whether a number is odd or even?

我不知道我应该在我的代码中添加哪一部分,这个 python 对我来说是新的,你能帮我吗?

您需要更改范围以也使用 n。

def odd_numbers(n):
    return [x for x in range(0, n+1) if x%2 != 0]
def odd_numbers(n):
    return [x for x in range(1, n+1) if x % 2 ==1]

这也是正确的,指定范围的步长:

def odd_numbers(n):
    return [x for x in range(1, n+1, 2) if x % 1 == 0]
def odd_numbers(n):
    return [x for x in range(0,n+1) if x%2 > 0 ]

这对我也有效,但我不确定在测试奇数值(!= 0 或 > 0)时哪个是最佳实践。那么哪个选项是最佳做法?

而不是像之前建议的那样从 0 开始丢失一次迭代:

def odd_numbers(n):
    return [x for x in range(0, n+1) if x % 2 != 0]

从1开始加速:

def odd_numbers(n):
    return [x for x in range(1, n+1) if x % 2 != 0]