How to convert 2d list into 3d?

Question:

I would to create a bracket after the lowest number. I have a short example below

A = [[],
 [2,3],
 [2,5,7,10],
 [5,10], 
 [15,20,21],
 [20,22],
 [20,27,36],
 [21,23],
 [32,35,40]
]

I would like my results to be like this

B = [
 [[2,3], [2,5,7,10]],
 [[5,10]],
 [[15,20,21]],
 [[20,22], [20,27,36]],
 [[21,23]],
 [[32,35,40]]
]
Asked By: Chris

||

Answers:

You can use itertools.groupby to group the lists by the 0-index value; then use list(g) on each of the groups to add the nesting you require. Note you need to filter out any empty lists first:

import itertools

A = [[2,3],[2,5,7,10],[5,10],[15,20,21], [20,22],[20,27,36],[],[21,23],[32,35,40]]
A2 = [l for l in A if len(l)]
B = [list(g) for _, g in itertools.groupby(A2, key=lambda v:v[0])]
print(B)

Output:

[
 [[2, 3], [2, 5, 7, 10]],
 [[5, 10]],
 [[15, 20, 21]],
 [[20, 22], [20, 27, 36]],
 [[21, 23]],
 [[32, 35, 40]]
]
Answered By: Nick

You can use a loop to iterate through the lists in A, find the lowest number in each list, and then create a new list in B with the sublists containing that lowest number. Here’s some Python code that should do what you want:

A = [ [2,3],
 [2,5,7,10],
 [5,10], 
 [15,20,21],
 [20,22],
 [20,27,36],
 [21,23],
 [32,35,40]
]

B = []
for lst in A:
    min_num = min(lst)
    found = False
    for sublist in B:
        if min_num in sublist:
            sublist.append(lst)
            found = True
            break
    if not found:
        B.append([lst])

print(B)

This should output:

[
 [[2, 3], [2, 5, 7, 10]],
 [[5, 10]],
 [[15, 20, 21]],
 [[20, 22], [20, 27, 36]],
 [[21, 23]],
 [[32, 35, 40]]
]

The code first initializes an empty list B, and then iterates through each sublist in A. For each sublist, it finds the minimum number using the min function.

Then it checks if there is already a sublist in B that contains that minimum number. If there is, it appends the current sublist to that existing sublist. If there isn’t, it creates a new sublist in B with the current sublist.

After iterating through all the sublists in A, the final value of B should contain the sublists grouped according to the lowest number.

Answered By: Mithlesh Upadhyay