如何对列表中相同值的元素进行有序分组?
有序分组列表中相同值元素的方法
针对你给出的列表 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
相关产品推荐
相关产品推荐

