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

如何不使用sorted函数按类型对Python列表元素分组?

问题描述

现有列表:

lst =  [4,67,8, 'not found', 32, 'missing', 21, 23, 'warning', 'alert', 2.01, [], {}]

希望创建按元素类型分组的新列表,预期结果为:

new =  [4,67,8, 32, 21, 23, 2.01,'not found','missing','warning', 'alert', [], {}]

已通过以下代码获取元素的唯一类型集合{int, float, str, list, dict}:

type_list = []
for i in lst:
    type_list.append(type(i))

type_set = set(type_list)

但后续分组代码无法得到预期结果:

new =  [4,67,8, 32, 21, 23, 2.01,'not found','missing','warning', 'alert', [], {}]

for index, data_type in enumerate(list(type_set)):
  tel = list(filter(lambda x : (index, data_type), lst))
print(tel)

需要在不使用sorted函数的前提下实现按类型分组。


解决方案

原代码问题分析

你的filter逻辑完全错误:lambda x : (index, data_type)这个表达式永远返回真值,所以每次filter都会返回整个列表,循环结束后只保留最后一次的结果,自然得不到分组效果。另外,集合是无序的,直接遍历type_set无法保证类型顺序符合预期。

正确实现方式

步骤1:明确类型优先级顺序

因为集合无序,必须先指定你想要的分组顺序:int→float→str→list→dict,这和你预期结果的分组顺序一致。

步骤2:按类型收集元素

依次遍历每个目标类型,从原列表中筛选出对应类型的元素,最后拼接所有结果:

lst =  [4,67,8, 'not found', 32, 'missing', 21, 23, 'warning', 'alert', 2.01, [], {}]
# 定义目标类型的优先级顺序
target_types = [int, float, str, list, dict]
new = []

for t in target_types:
    # 筛选当前类型的所有元素并添加到结果列表
    new.extend(item for item in lst if type(item) == t)

print(new)

运行结果:

[4, 67, 8, 32, 21, 23, 2.01, 'not found', 'missing', 'warning', 'alert', [], {}]

兼容优化(可选)

如果不想手动写target_types,可以基于你之前获取的type_set,按优先级筛选出存在的类型,兼容原列表缺少某些类型的情况:

lst =  [4,67,8, 'not found', 32, 'missing', 21, 23, 'warning', 'alert', 2.01, [], {}]

# 先获取唯一类型集合
type_list = []
for i in lst:
    type_list.append(type(i))
type_set = set(type_list)

# 按优先级筛选出存在的类型
priority_order = [int, float, str, list, dict]
target_types = [t for t in priority_order if t in type_set]

new = []
for t in target_types:
    new.extend(item for item in lst if type(item) == t)

print(new)

内容的提问来源于stack exchange,提问作者RamAlx

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 05:42:57