Python 我只想返回列表中的奇数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41676212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:25:47  来源:igfitidea点击:

I want to return only the odd numbers in a list

python

提问by I liek to c0d3

My issue here is that the code filters out the even numbers correctly which is what I want, however it stops at seven and doesn't display number 9 which is what I would expect it to do. I've tried going over my code but I can't seem to find the issue

我的问题是代码正确过滤了偶数,这正是我想要的,但是它停在 7 处并且不显示数字 9,这是我期望它做的。我试过检查我的代码,但我似乎找不到问题

def remove_even(numbers) :
    new_list = []
    for i in range(0,len(numbers)-1) :
        if i % 2 != 0 :
            new_list.append(i)
    return new_list
l = [1,2,3,4,5,6,7,8,9,10]
print(remove_even(l))

回答by Cory Kramer

You should just directly loop through your values instead of indices

您应该直接遍历您的值而不是索引

for i in numbers:

Otherwise if you wanted to use rangeyou would have to index into your list

否则,如果您想使用range,则必须索引到您的list

for i in range(0, len(numbers)):
    if numbers[i] % 2 != 0 :
        new_list.append(numbers[i])

For brevity, list comprehensions are well-suited for this type of task

为简洁起见,列表推导式非常适合此类任务

>>> new_list = [num for num in l if num % 2 == 1]
>>> new_list
[1, 3, 5, 7, 9]

回答by e4c5

[k for k in l if k %2]

Is a simple list comprehensionthat returns

是一个简单的列表推导式返回

[1, 3, 5, 7, 9]

回答by Ajay Rawat

This is because you are starting your range() function of your for loop from 0 and ending at len(numbers)-1 (which is 9 in your case), python range() already will run till end-1:

这是因为您从 0 开始 for 循环的 range() 函数并以 len(numbers)-1(在您的情况下为 9)结束,python range() 已经将运行到 end-1:

for eg:

例如:

for i in range(0,9):
    print(i)

will print no's: 0 1 2 3 4 5 6 7 8

将打印编号:0 1 2 3 4 5 6 7 8

and that's why your 9 is not here in the output.

这就是为什么您的 9 不在输出中的原因。

you don't have to start your loop from 0. If you are starting from 0 you can arrange your for loop like this:

你不必从 0 开始你的循环。如果你从 0 开始,你可以像这样安排你的 for 循环:

1)

1)

for i in range(0, len(numbers)+1)

2)Or you can code like more pythonic way.

2)或者你可以像更pythonic的方式编码。

def remove_even(numbers) :
    new_list = []
    for i in numbers :
        if i % 2 != 0 :
            new_list.append(i)
    return new_list

回答by Mike Turner

#simpliest way of doing it
mylist = [1,2,3,4,5,6,7,8,9,10,11]
for x in mylist:
    if x % 2 == 1: #this displays odd numbers
        print(x)

回答by Gauthier Feuillen

numbers = [1,2,3,4,5,6,7,8,9,10]

odds = [i for i in numbers if i%2!=0]