区分Python中的“character”和“numeric”数据类型

2024-03-28 13:15:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道是否有一种简单的方法来区分Python中的字符和数字数据类型(例如int/double/float等)。理想情况下,我希望能够区分标量和列表。你知道吗

简而言之,我希望能够编写一个函数easy_type,它将执行以下操作:

>>> easy_type(["hello", "world"])  
   "character"
>>> easy_type("hello")  
   "character"
>>> easy_type(['1.0', '0.0'])  
   "numeric"
>>> easy_type([0, 1, 2])  
   "numeric"
>>> easy_type(0.100)  
   "numeric"

Tags: 方法hellotypeeasy情况数字float字符
3条回答

因为您有多种类型的数据,所以您可能希望使用递归函数获取单个项的类型,如下所示

def get_type(data):
    if isinstance(data, list):
        types = {get_type(item) for item in data}
        # If all elements of the list are of the same type
        if len(types) == 1:
            return next(iter(types))
        # if not, return "multiple"
        else:
            return "multiple"
    elif isinstance(data, str):
        # Check if the string has only numbers or it is a float number
        return "numeric" if data.isdigit() or is_float(data) else "character"
    elif isinstance(data, int) or isinstance(data, float):
        return "numeric"

助手函数is_float的定义如下

def is_float(data):
    try:
        float(data)
        return True
    except ValueError:
        return False

还有测试

assert(get_type(["hello", "world"]) == "character")
assert(get_type("hello") == "character")
assert(get_type(['1.0', '0.0']) == "numeric")
assert(get_type([0, 1, 2]) == "numeric")
assert(get_type(0.100) == "numeric")

要为标量处理"character""numeric",请执行以下操作:

def easy_type(ob):
    try:
        float(ob)
        return "numeric"
    except ValueError:
        return "character"

要以类似方式处理列表,请假设列表的所有元素都是同一类型的,并且列表不是嵌套的,也不是空的:

def easy_type(ob):
    if isinstance(ob, list):
        return mytype(ob[0])
    try:
        float(ob)
        return "numeric"
    except ValueError:
        return "character"

也要处理"multiple"

def easy_type(ob):
    if isinstance(ob, list):
        types = set((mytype(o) for o in ob))
        if len(types) > 1:
            return "multiple"
        else:
            return types.pop()
    try:
        float(ob)
        return "numeric"
    except ValueError:
        return "character"

您可以使用built-in ^{} function获得您想要的大部分内容:

>>> type("hello").__name__
'str'
>>> type(1).__name__
'int'
>>> type(1.5).__name__
'float'
>>> type(["hello", "world"]).__name__
'list'

您需要决定如何处理列表,特别是因为列表可以包含不同类型的元素。你知道吗

相关问题 更多 >