简体   繁体   English

使用filter()过滤“无”输出Python

[英]Filter 'None' output Python using filter()

I am getting an error when trying to filter the 'None' output, when using the filter function in Python, here is my code: 尝试过滤“无”输出时出现错误,在Python中使用过滤器功能时,这是我的代码:

def my_function(x):
if (x % 2 == 0):
    x=filter(None, x)
    return(x)

for x in range(1, 10):
    sum=sum+(my_function(x))
    print(sum)

and Python cannot make the sum as the None output cannot be removed, because it is "adding" this 并且Python无法计算总和,因为无法删除None输出,因为它正在“添加”此

None
2
None
4
None
6
None
8
None

and not this 不是这个

2
4
6
8

Several errors here. 这里有几个错误。 First, don't use sum because is a builtin python function name. 首先,不要使用sum因为它是内置的python函数名称。 The, filter expect an iterable to work with, and a function. filter期望可迭代的函数和一个函数。 None is not a function it will use the identity function (which returns the same value it takes) (tip by @bro-grammer). None不是一个函数,它将使用identity函数(返回相同的值)(@ bro-grammer提示)。 Since x is not an iterable you can't use filter on it. 由于x不可迭代,因此无法对其使用过滤器。

You want to check if x is even: 您要检查x是否为偶数:

def my_function(x):
    if (x % 2 == 0):
        return True
    return False

sumation = 0
for x in range(1, 10):
    if my_function(x):
        sumation += x
print(sumation)

The other option using actual filter and sum is : 使用实际filtersum的另一个选项是:

>>> def my_function(x):
...     if (x % 2 == 0):
...         return True
...     return False
... 
>>> sumation = sum(filter(my_function, range(1, 10)))
>>> sumation
20

And the pythonic way of doing this is with a generator and sum : pythonic的方法是使用generator和sum

>>> sum(x for x in range(1, 10) if x % 2 == 0 )
20

I guess you're trying to use the filter function in a wrong way. 我猜您正在尝试以错误的方式使用过滤器功能。 You could use this as an example with this code: 您可以将以下代码用作示例:

def my_function(x):
    if (x % 2 == 0):
        return True
    else:
        return False

alist = filter(my_function,list(range(1,10)))
print(sum(alist))

Hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM