我如何编写一个 returns 所有负数的函数,并检查输入是否仅为整数和浮点数?

How can I write a function that returns all negative numbers as well as checks if the input are only integers and floating point numbers?

编写一个函数 find_negatives,它接受一个数字列表 l 作为参数,returns 一个包含 l 中所有负数的列表。如果 l 中没有负数,它 returns 一个空列表。

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 不是列表,它 returns 字符串“Invalid parameter type!” 如果 l 中的任何元素既不是整数也不是浮点数,则它 returns 字符串“无效参数值!”

到目前为止我有什么

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

我不确定如何进行。我不确定如何检查列表中的每种类型

您可以尝试以下代码:

def find_negatives2(l):
    l_tmp1 = []
    if not isinstance(l, list):
        return "Invalid parameter type!"
    else:
       for num in l:
         if not (isinstance(num, float) or isinstance(num, int)):
           return "Invalid parameter value!"
         else:
           if num < 0:
             l_tmp1.append(num)
    return l_tmp1
assert find_negatives2([8, -3.5, 0, 2, -2.7, -1.9, 0.0])      == [-3.5, -2.7, -1.9]
assert find_negatives2([0, 1, 2, 3, 4, 5])                    == []
assert find_negatives2(-8)                                    == 'Invalid parameter type!'
assert find_negatives2({8, -3.5, 0, 2, -2.7, -1.9, 0.0})      == 'Invalid parameter type!'
assert find_negatives2([8, -3.5, 0, 2, "-2.7", -1.9, 0.0])    == 'Invalid parameter value!'
assert find_negatives2([8, -3.5, 0, 2, [-2.7], -1.9, 0.0])    == 'Invalid parameter value!'

所有断言都将得到验证。

说明

isinstance 检查它的第一个参数是否是它的第二个参数的实例。使用此功能,您可以检查任何变量类型。请注意,使用 type(l) != list 不是检查变量类型的好方法。如果您有兴趣知道原因,这篇 link 可能会对您有所帮助。

你走在正确的轨道上;你只需要为类型比较做一个循环:

# (...)
else:
    for num in l:
        if type(num) not in (int, float):
            return "Invalid parameter type!"
        # (...)

您可以通过以下方式实现您的目标:

def find_negatives(l):
    if type(l) != list or any(str(x).isnumeric() for x in l) == False:
        return 'Invalid parameter type!'
    l_tmp = []
    for num in l:
        if num < 0:
            l_tmp.append(num)
    return l_tmp

您所要做的就是检查输入是否为列表,以及输入中是否有任何元素不是数字。