【问题标题】:How to check if all items in list are string如何检查列表中的所有项目是否都是字符串
【发布时间】:2016-09-18 08:59:38
【问题描述】:

如果我在python中有一个列表,是否有一个函数可以告诉我列表中的所有项目是否都是字符串?

例如: ["one", "two", 3] 将返回 False,["one", "two", "three"] 将返回 True。

【问题讨论】:

标签: python python-3.x


【解决方案1】:

回答@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"]) 出[5]:真

【讨论】:

    【解决方案2】:

    只需使用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
    

    【讨论】:

    • 还有一个问题,有没有办法检查列表中是否没有数字字符串。例如:["one", "two", "3"] 将返回 false
    • @TekhenyGhemor - isinstance(item, str) and not item.lstrip('-').isdigit() 用于零或正整数。如果您想检查浮点数、复数等,它会涉及更多。
    • @XamuelSchulman - 你的意思是摆脱 all() 和生成器表达式(不是列表理解)并创建传统的 for..else 循环吗?还是您的意思是将当前代码分成多行?我看不出这两种方法有什么帮助。这已经简洁、清晰、规范。
    猜你喜欢
    • 2015-10-03
    • 2018-02-09
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    • 2011-06-18
    • 2011-04-25
    • 2021-03-12
    相关资源
    最近更新 更多