简体   繁体   English

接受 1 个可迭代参数并添加列表中的所有对象(如果它们是 int 或 float)的函数?

[英]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.我需要创建一个函数,该函数接受一个可迭代参数并添加列表中的所有对象(如果它们是 int 或 float)。 Objects that are not int or float should be skipped and a sum of int and float should be returned.应该跳过不是 int 或 float 的对象,并且应该返回 int 和 float 的总和。 I need to use loop and isinstance function.我需要使用循环和 isinstance 函数。 If there is an input [5.3, 2, "Book", True], return float object should equal to 7.3.如果有输入 [5.3, 2, "Book", True],则返回浮点对象应等于 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.我得到 8.3 作为答案。

This is because float(True) equals 1 .这是因为float(True)等于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))

暂无
暂无

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

相关问题 Function 接受一个 Int 和一个 List - Function that takes an Int and a List 列表接受可迭代对象作为输入。 但是,当输入为int或float时,例如list(1),则不接受此输入。 为什么? - Lists accept iterable objects as inputs. However, when the input is an int or float, e.g. list(1), this is not accepted. Why? 将iterable作为参数的函数是否总是接受迭代器? - Does a function which takes iterable as parameter always accept iterator? 'int'对象在列表上不可迭代 - 'int' object is not iterable on list 如何编写一个带有int或float的C函数? - How can I write a C function that takes either an int or a float? TypeError:内置max函数中的列表上的'float'对象不可迭代 - TypeError: 'float' object is not iterable on a list in built in max function 类型错误:尝试从浮动列表中选择特定对象时,“浮动”对象不可迭代 - TypeError: 'float' object is not iterable when attempting to choose specific objects from a float list python试图将列表作为函数TypeError中的变量传递:'int'对象不可迭代 - python trying to pass list in as variable in function TypeError: 'int' object is not iterable 如何修复列表 function 中的“'int' object 不可迭代”错误? - How do I fix an "'int' object is not iterable" error in list function? 对象列表不可迭代,并且调用变量在其他函数中 - List of objects is not iterable & call variable being in other function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM