首页 > 解决方案 > 将相似的项目打包到列表中

问题描述

我正在学习算法,并且出现了这个问题:

给定一个整数数组,将连续元素打包到子列表中。

例如,给定列表 [4, 4, 1, 6, 6, 6, 1, 1, 1, 1],返回 [[4, 4], [1], [6, 6, 6], [1 , 1, 1, 1]]。

注意:如果列表中只有一次出现,则它仍应位于其自己的子列表中。

我创建了以下解决方案:

def solve(nums):
    packed = []
    lastElement = nums[0]
    currPack = []
    for i, num in enumerate(nums):
        newPack = []
        if lastElement == num:
            currPack.append(num)
        else:
            newPack.append(num)
            packed.append(currPack)
            currPack = newPack
            
        lastElement = num
    
    packed.append(currPack)
    return packed

 nums = [4,4,1,6,6,6,1,1,1,1]
 solve(nums)
 # [[4,4], [1], [6,6,6], [1,1,1,1]]

它正在工作,但正如您所见,它不是很干净。我该如何改进呢?

标签: python

解决方案


你可以试试itertools.groupby

>>> from itertools import groupby
>>> x = [4, 4, 1, 6, 6, 6, 1, 1, 1, 1]
>>> new_list = [list(group) for _, group in groupby(x)]
>>> new_list
[[4, 4], [1], [6, 6, 6], [1, 1, 1, 1]]
>>>

另一种方法是:

>>> master_list, new_list = [], []
>>> for elem in x:
...     if not new_list:
...             new_list.append(elem)
...     elif elem == new_list[-1]:
...             new_list.append(elem)
...     else:
...             master_list.append(new_list)
...             new_list = [elem]
>>> master_list.append(new_list)
>>> master_list
[[4, 4], [1], [6, 6, 6], [1, 1, 1, 1]]

推荐阅读