简体   繁体   中英

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:

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

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. The, filter expect an iterable to work with, and a function. None is not a function it will use the identity function (which returns the same value it takes) (tip by @bro-grammer). Since x is not an iterable you can't use filter on it.

You want to check if x is even:

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 :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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