有没有一种方法可以将“字符串数组”设置为函数中参数的类型?

时间:2019-05-02 08:13:42

标签: python list types parameters

如果参数是字符串数组,我想检查参数是否传递给函数。

就像将函数的参数类型设置为“字符串数组”一样。 但是我不想遍历整个数组以查找无字符串元素。

有这样的类型吗?

4 个答案:

答案 0 :(得分:2)

>>> isinstance(["abc", "def", "ghi", "jkl"], list)
True
>>> isinstance(50, list)
False

您可以在函数内部使用此命令来检查您的参数是否为列表。

答案 1 :(得分:1)

使其成为防弹符号的方法是在函数中检查它们(严重地迭代元素),但是对理解使用all会使评估变得懒惰,并且会在不是字符串实例:

def foo(my_str_list):
    is_list = isinstance(my_str_list, list) 
    are_strings = all(isinstance(x, str) for x in my_str_list)
    if not is_list or not are_strings:
        raise TypeError("Funtion argument should be a list of strings.")
    ...

答案 2 :(得分:1)

lambda函数会起作用吗?

def check_arr_str(li):

    #Filter out elements which are of type string
    res = list(filter(lambda x: isinstance(x,str), li))

    #If length of original and filtered list match, all elements are strings, otherwise not
    return (len(res) == len(li) and isinstance(li, list))

输出看起来像

print(check_arr_str(['a','b']))
#True
print(check_arr_str(['a','b', 1]))
#False
print(check_arr_str(['a','b', {}, []]))
#False
print(check_arr_str('a'))
#False

如果需要例外,我们可以如下更改功能。

def check_arr_str(li):

    res = list(filter(lambda x: isinstance(x,str), li))
    if (len(res) == len(li) and isinstance(li, list)):
        raise TypeError('I am expecting list of strings')

我们可以执行此操作的另一种方法是使用any检查列表中是否有不是字符串的项目,或者参数不是列表(感谢@Netwave的建议)

def check_arr_str(li):

    #Check if any instance of the list is not a string
    flag = any(not isinstance(i,str) for i in li)

    #If any instance of an item  in the list not being a list, or the input itself not being a list is found, throw exception
    if (flag or not isinstance(li, list)):
        raise TypeError('I am expecting list of strings')

答案 3 :(得分:1)

尝试一下:

l = ["abc", "def", "ghi", "jkl"]  
isinstance(l, list) and all(isinstance(i,str) for i in l)

输出:

In [1]: a = ["abc", "def", "ghi", "jkl"]                                        

In [2]: isinstance(a, list) and all(isinstance(i,str) for i in a)               
Out[2]: True

In [3]: a = ["abc", "def", "ghi", "jkl",2]                                      

In [4]: isinstance(a, list) and all(isinstance(i,str) for i in a)               
Out[4]: False