How can I find same values in a list and group together a new list?

后端 未结 6 1661
感情败类
感情败类 2020-12-03 07:11

From this list:

N = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]

I\'m trying to create:

L = [[1],[2,2],[3,3,3],[4,4,4,4],[5,5,5,5,5]]
         


        
6条回答
  •  执念已碎
    2020-12-03 08:01

    Another slightly different solution that doesn't rely on itertools:

    #!/usr/bin/env python
    
    def group(items):
        """
        groups a sorted list of integers into sublists based on the integer key
        """
        if len(items) == 0:
            return []
    
        grouped_items = []
        prev_item, rest_items = items[0], items[1:]
    
        subgroup = [prev_item]
        for item in rest_items:
            if item != prev_item:
                grouped_items.append(subgroup)
                subgroup = []
            subgroup.append(item)
            prev_item = item
    
        grouped_items.append(subgroup)
        return grouped_items
    
    print group([1,2,2,3,3,3,4,4,4,4,5,5,5,5,5])
    # [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5]]
    

提交回复
热议问题