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

如何对列表中相同值的元素进行有序分组?

有序分组列表中相同值元素的方法

针对你给出的列表 arr = [1,4,5,1,6,4,7,5],要实现按元素首次出现顺序分组得到 [[1,1],[4,4],[5,5],[6],[7]],可以用以下几种Python实现方式:

方法一:利用普通字典(Python 3.7+)

Python 3.7及以上版本的字典会保留键的插入顺序,直接遍历原列表即可按首次出现顺序分组:

arr = [1,4,5,1,6,4,7,5]
group_dict = {}
for num in arr:
    if num not in group_dict:
        group_dict[num] = []
    group_dict[num].append(num)
result = list(group_dict.values())
print(result)  # 输出: [[1, 1], [4, 4], [5, 5], [6], [7]]

方法二:使用OrderedDict(兼容Python 3.6及更早版本)

如果需要兼容更早的Python版本,可借助collections.OrderedDict来保证顺序:

from collections import OrderedDict

arr = [1,4,5,1,6,4,7,5]
group_dict = OrderedDict()
for num in arr:
    if num not in group_dict:
        group_dict[num] = []
    group_dict[num].append(num)
result = list(group_dict.values())
print(result)

方法三:用itertools.groupby(按元素大小排序分组)

如果接受按元素大小排序后的分组顺序,可使用itertools.groupby,但需要先对列表排序:

from itertools import groupby

arr = [1,4,5,1,6,4,7,5]
sorted_arr = sorted(arr)
result = [list(group) for key, group in groupby(sorted_arr)]
print(result)  # 输出: [[1, 1], [4, 4], [5, 5], [6], [7]]

注意:这种方法的分组顺序是元素的自然排序顺序,若原列表中元素首次出现顺序和排序顺序不一致,结果分组顺序也会不同。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 06:12:08