8 python parameters types list
我想在将参数传递给函数时检查参数是否是字符串数组。
就像将函数参数的类型设置为“字符串数组”一样。但我不想循环遍历数组寻找非字符串元素。
有这样的类型吗?
Kaw*_*aLo 10
您可以使用最新 python 版本的输入(在 3.9 上测试),如@Netwave 在评论中建议的那样:
def my_function(a: list[str]):
# You code
Run Code Online (Sandbox Code Playgroud)
它将按预期掉毛:
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))
Run Code Online (Sandbox Code Playgroud)
输出看起来像
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
Run Code Online (Sandbox Code Playgroud)
如果需要异常,我们可以按如下方式更改函数。
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')
Run Code Online (Sandbox Code Playgroud)
我们可以做到这一点的另一种方法是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')
Run Code Online (Sandbox Code Playgroud)