Skip to main content
 首页 » 编程设计

python之Python中区分 'character'和 'numeric'数据类型

2024年10月25日9bhlsheji

我想知道在 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" 

请您参考如下方法:

由于您有多种类型的数据,您可能希望使用递归函数获取单个项目的类型,就像这样

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")