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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With