Search code examples
pythonlistlist-comprehension

List comprehension to get a 2D list of the same values


I have the following digits:

arr = [4, 5, 5, 5, 6, 6, 4, 1, 4, 4, 3, 6, 6, 3, 6, 1, 4, 5, 5, 5]

I want to create a list comprehension that will match me all the same values in a 2d array of lists like:

[[1, 1], [3, 3], [4, 4, 4, 4, 4], [5, 5, 5, 5, 5, 5], [6, 6, 6, 6, 6]]

I tried something like:

listArr = sorted(arr)

unfortunately I don't know how to put the sorted numbers into a 2D array of lists.


Solution

  • After sorting, you can use itertools.groupby.

    >>> L = [4, 5, 5, 5, 6, 6, 4, 1, 4, 4, 3, 6, 6, 3, 6, 1, 4, 5, 5, 5]
    >>> from itertools import groupby
    >>> [list(group) for _key, group in groupby(sorted(L))]
    [[1, 1], [3, 3], [4, 4, 4, 4, 4], [5, 5, 5, 5, 5, 5], [6, 6, 6, 6, 6]]
    

    However, it may be more efficient to sort after, like in Andrej's answer, since it would mean fewer swaps.