繁体   English   中英

有没有办法将“字符串数组”设置为 function 中的参数类型?

[英]Is there a way to set "array of strings" as a type for a parameter in a function?

如果参数是字符串数组,我想检查 arguments 到 function 的传递。

就像将 function 的参数的类型设置为“字符串数组”一样。 但我不想遍历数组寻找非字符串元素。

有这样的类型吗?

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

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

使其安全的方法是在函数中检查它们(对元素进行迭代),但是将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.")
    ...

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

尝试这个:

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

正如@Netwave 在评论中所建议的那样,您可以对最近的 python 版本(在 3.9 上测试)使用打字:

def my_function(a: list[str]):
  # You code

这将按预期进行:

pycharm linting 示例

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM