如何在Python中按数据类型分类列表元素并优化冗余代码
问题
给定列表:
li=[22 , True , 22/7 , {"Staat":"Deutschland" , "Stadt" : "Berlin"} , 69 , ["Python" , "C++" , "C#"] , ("Kairo" , "Berlin" , "Amsterdam") , False , "Apfel" , 55 ]
需要将列表中的元素按数据类型(int、str、dict等)分别归类到不同列表中。目前使用的逐个判断类型的代码不仅冗余冗长,还无法将同类型元素合并到同一个列表中,需要优化实现需求。
现有代码:
for x in li: if type(x) == float: double = x print("double" ,double ) elif type(x) == str: strings = x print("strings" ,strings)
优化实现方案
用字典来存储不同类型对应的元素列表,遍历原列表时自动判断元素类型并归类,无需手动写大量if/elif分支,扩展性更强。
基础实现代码
li = [22, True, 22/7, {"Staat": "Deutschland", "Stadt": "Berlin"}, 69, ["Python", "C++", "C#"], ("Kairo", "Berlin", "Amsterdam"), False, "Apfel", 55] # 初始化字典,键为数据类型,值为对应类型的元素列表 type_groups = {} for item in li: item_type = type(item) # 若该类型未在字典中,先创建空列表 if item_type not in type_groups: type_groups[item_type] = [] # 将元素追加到对应类型的列表中 type_groups[item_type].append(item) # 打印所有归类结果 for data_type, elements in type_groups.items(): print(f"{data_type.__name__}: {elements}")
代码说明
- 利用
type(item)获取元素的类型作为字典的键,自动映射到存储该类型元素的列表,新增类型时无需修改代码。 - 遍历过程中自动为新类型创建空列表,再添加元素,实现自动归类。
- 可以通过
type_groups[int]、type_groups[str]等方式直接提取对应类型的元素列表。
关于布尔值的特殊处理
Python中bool是int的子类,type(True)会返回bool类型。如果需要将布尔值单独归类(而非归到整数类),可以用isinstance做更细致的判断:
type_groups = {} for item in li: # 优先区分布尔值,避免被归为int if isinstance(item, bool): target_type = bool elif isinstance(item, int): target_type = int else: target_type = type(item) if target_type not in type_groups: type_groups[target_type] = [] type_groups[target_type].append(item) for data_type, elements in type_groups.items(): print(f"{data_type.__name__}: {elements}")
如果不需要区分布尔值和整数,直接用isinstance(item, int)会把True、False也归到整数列表中。
内容的提问来源于stack exchange,提问作者Ziad Abouhalawa
相关产品推荐
相关产品推荐

