You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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}")

代码说明

  1. 利用type(item)获取元素的类型作为字典的键,自动映射到存储该类型元素的列表,新增类型时无需修改代码。
  2. 遍历过程中自动为新类型创建空列表,再添加元素,实现自动归类。
  3. 可以通过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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 03:30:54