[英]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.