我只想返回列表中的奇数 [英] I want to return only the odd numbers in a list

查看:33
本文介绍了我只想返回列表中的奇数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是代码可以正确过滤掉我想要的偶数,但是它停在了7位并且没有显示9位,这正是我期望的.我已经尝试过检查代码,但似乎找不到问题

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

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))

推荐答案

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

You should just directly loop through your values instead of indices

for i in numbers:

否则,如果要使用 range ,则必须索引到列表

Otherwise if you wanted to use range you would have to index into your 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]

这篇关于我只想返回列表中的奇数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆