简体   繁体   English

如何检查列表中的所有项目是否都是字符串

[英]How to check if all items in list are string

If I have a list in python, is there a function to tell me if all the items in the list are strings?如果我在 python 中有一个列表,是否有一个 function 告诉我列表中的所有项目是否都是字符串?

For Example: ["one", "two", 3] would return False , and ["one", "two", "three"] would return True .例如: ["one", "two", 3]将返回False ,而["one", "two", "three"]将返回True

Just use all() and check for types with isinstance() . 只需使用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

Answering @TekhenyGhemor's follow-up question: is there a way to check if no numerical strings are in a list. 回答@TekhenyGhemor的后续问题:有没有办法检查列表中是否没有数字字符串。 For example: ["one", "two", "3"] would return false 例如:[“one”,“two”,“3”]将返回false

Yes. 是。 You can convert the string to a number and make sure that it raises an exception: 您可以将字符串转换为数字,并确保它引发异常:

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)

Checking: 检查:

>>> valid_list(["one", "two", "3"])
False

>>> valid_list(["one", "two", "3a"])
True

>>> valid_list(["one", "two", 0])
False

In [5]: valid_list(["one", "two", "three"]) Out[5]: True 在[5]中:valid_list([“one”,“two”,“three”])Out [5]:True

Another way to accomplish this is using the map() function:另一种方法是使用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.

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