【发布时间】:2022-02-21 07:29:50
【问题描述】:
编写一个函数 find_negatives,它接受一个数字列表 l 作为参数,并返回 l 中所有负数的列表。如果 l 中没有负数,则返回一个空列表。
def find_negatives(l):
l_tmp = []
for num in l:
if num < 0:
l_tmp.append(num)
return l_tmp
#Examples
find_negatives([8, -3.5, 0, 2, -2.7, -1.9, 0.0]) # Expected output: [-3.5, -2.7, -1.9]
find_negatives([0, 1, 2, 3, 4, 5]) # Expected output: []
这是我在下面遇到问题的部分:
编写一个函数 find_negatives2,其工作原理与 find_negatives 相同,并添加以下两个内容:
如果 l 不是列表,则返回字符串“无效的参数类型!” 如果 l 中的任何元素既不是整数也不是浮点数,则返回字符串“Invalid parameter value!”
我目前所拥有的
def find_negatives2(l):
l_tmp1 = []
if type(l) != list:
return "Invalid parameter type!"
else:
for num in l:
Examples:
find_negatives2([8, -3.5, 0, 2, -2.7, -1.9, 0.0]) # Expected output: [-3.5, -2.7, -1.9]
find_negatives2([0, 1, 2, 3, 4, 5]) # Expected output: []
find_negatives2(-8) # Expected output: 'Invalid parameter type!'
find_negatives2({8, -3.5, 0, 2, -2.7, -1.9, 0.0}) # Expected output: 'Invalid parameter type!'
find_negatives2([8, -3.5, 0, 2, "-2.7", -1.9, 0.0]) # Expected output: 'Invalid parameter value!'
find_negatives2([8, -3.5, 0, 2, [-2.7], -1.9, 0.0]) # Expected output: 'Invalid parameter value!'
我不确定如何继续。我不确定如何检查列表中的每种类型
【问题讨论】:
-
有什么问题?是有错误还是不知道如何处理?
-
我不知道该怎么做。我不确定如何检查列表中的每种类型