[英]How to check if all items in list are string
如果我在 python 中有一个列表,是否有一个 function 告诉我列表中的所有项目是否都是字符串?
例如: ["one", "two", 3]
将返回False
,而["one", "two", "three"]
将返回True
。
只需使用all()
并使用isinstance()
检查类型。
>>> l = ["one", "two", 3]
>>> all(isinstance(item, str) for item in l)
False
>>> l = ["one", "two", '3']
>>> all(isinstance(item, str) for item in l)
True
回答@TekhenyGhemor的后续问题:有没有办法检查列表中是否没有数字字符串。 例如:[“one”,“two”,“3”]将返回false
是。 您可以将字符串转换为数字,并确保它引发异常:
def isfloatstr(x):
try:
float(x)
return True
except ValueError:
return False
def valid_list(L):
return all((isinstance(el, str) and not isfloatstr(el)) for el in L)
检查:
>>> valid_list(["one", "two", "3"])
False
>>> valid_list(["one", "two", "3a"])
True
>>> valid_list(["one", "two", 0])
False
在[5]中:valid_list([“one”,“two”,“three”])Out [5]:True
另一种方法是使用map()
function:
>>> all(map(lambda x: isinstance(x, str), ['one', 'two', 3]))
False
>>> all(map(lambda x: isinstance(x, str), ['one', 'two', 'three']))
True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.