将类似的项目打包到列表中

2024-09-28 01:33:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习算法,有一个问题:

Given an array of integers, pack consecutive elements into sublists.

For example, given the list [4, 4, 1, 6, 6, 6, 1, 1, 1, 1], return [[4, 4], [1], [6, 6, 6], [1, 1, 1, 1]].

Note: If there's only one occurrence in the list it should still be in its own sublist.

我创建了以下解决方案:

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]]

它正在工作,但正如你所看到的,它不是很干净。我该如何改进这一点


Tags: thein算法anreturnnumgivenlist
2条回答

试试这个:

from itertools import groupby

a = [4, 4, 1, 6, 6, 6, 1, 1, 1, 1]
new_list=[] 
for k,g in groupby(a): 
    new_list.append(list(g))

new_list将是您预期的结果

您可以尝试^{}

>>> 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]]

相关问题 更多 >

    热门问题