简体   繁体   中英

Function that takes 1 iterable parameter and adds all objects in the list if they are int or float?

I need to create a function that takes one iterable parameter and adds all of the objects in the list if they are an int or float. Objects that are not int or float should be skipped and a sum of int and float should be returned. I need to use loop and isinstance function. If there is an input [5.3, 2, "Book", True], return float object should equal to 7.3. So far I have:

def add_numbers_in_list(number_list):
    for x in number_list:
        try:
            yield float(x)
        except ValueError:
            pass
number_list = [5.3, 2, "Book", True]
print(sum(add_numbers_in_list(number_list)))

I'm getting 8.3 as an answer.

This is because float(True) equals 1 . To fix your code you can do this:

def add_numbers_in_list(number_list):
    for x in number_list:
       if type(x) in [float, int]: # Change over here
          yield float(x) 


number_list = [5.3, 2, "Book", True]
print(sum(add_numbers_in_list(number_list)))

If you would like to store the count and return it you can use the following script:

def add_numbers_in_list(number_list):
    count = 0
    for x in number_list:
       if type(x) in [float, int]:
          count += float(x) 
    return count


number_list = [5.3, 2, "Book", True]
print(add_numbers_in_list(number_list))

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