首页 > 解决方案 > 如何创建一个函数,将每个列表项标识为字符串、浮点数或整数,然后打印一个类似 [str, int....] 的列表

问题描述

我很难让它识别每个单独的列表项。我一直在尝试使用 [i] 但它不起作用......

def identify(list_obj):
    stats = {}
    for i in items:
        if type(list_obj) == int:
            print("int")
        if type(list_obj) == str:
            print("str")
        if type(list_obj) == float:
            print("float")
        else:
            print("null")
    return list_obj

print(identify(list5))   

标签: python-3.x

解决方案


你循环,items但你没有items在你的代码中声明。

所以你应该循环list_object指定每个的类型item

def identify(list_objects):
    """
    It takes a list of objects and specifies the type of each object in the list.
    """
    handler_dict = {
        int: 'int',
        str: 'str',
        float: 'float',
        list: 'list',
        dict: 'dict'
    }

    return [handler_dict.get(type(obj), 'unknown') for obj in list_objects]

测试

>>> list_objects = [1, 'a', [1, 2], {'a': 1}, 1.0]
>>> print(identify(list_objects))
out: ['int', 'str', 'list', 'dict', 'float']

推荐阅读