Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 409
JAdel Avatar asked Jan 25 '26 23:01

JAdel


1 Answers

You can create temporary dictionary to group the digits:

s = "4 5 5 5 6 6 4 1 4 4 3 6 6 3 6 1 4 5 5 5"

out = {}
for d in s.split():
    out.setdefault(d, []).append(int(d))

out = sorted(out.values())
print(out)

Prints:

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

If s is a list of numbers:

out = {}
for d in s:
    out.setdefault(d, []).append(d)

out = sorted(out.values())
print(out)
like image 50
Andrej Kesely Avatar answered Jan 28 '26 15:01

Andrej Kesely