The first poster is here. If I have a list containing a sublist with different information and I want to group all the subbooks with the same key value into a new sublist (for example, a unique-ify list based on key values), which is the most efficient way to do this ?
Example:
A = [[1,2,3], [1,3,7], [2,1,3], [8,9,6], [3,7,9], [2,3,8], [1,2,4]]
And I want to group all the sublists that have the same element in the index '0' into one new sublist, preferably keeping the original order:
B = [ [[1,2,3], [1,3,7], [1,2,4]], [[2,1,3],[2,3,8]], [[8,9,6]], [[3,7,9]] ]
I have solved this problem many times, but I would like to know if there is a more efficient way to do this. Yes, I can use the numpy package for this reason, but I'm interested in a list solution.
Typically, I would first have a uniquely-ify element in the first index in each sublist (using the set method, if I'm not worried about efficiency or order), and then iterate over the entire list, combining the signatures into a new sublist
def getUniqueList(list):
seen = []
for e in list:
if e not in seen:
seen.append(e)
return seen
def uniquify(list):
new_list = [item[0] for item in list]
return getUniqueList(new_list)
def rearrangeList(A, A_0):
B = []
for i in range(len(A_0)):
B.append([])
for i in range(len(A)):
index = A_0.index(A[i][0])
B[index].append(A[i])
return B
A = [[1,2,3], [1,3,7], [2,1,3], [8,9,6], [3,7,9], [2,3,8], [1,2,4]]
A_0 = uniquify(A)
B = rearrangeList(A, A_0)
print(B)
This should (I have not tested this, but this is how I encoded it):
B = [[[1,2,3], [1,3,7], [1,2,4]], [[2,1,3], [2,3,8]], [[8 , 9.6]], [[3,7,9]]]
I wanted to know if 1) the best way to do this in terms of efficiency, and 2) is there a way to do this in smaller steps (not necessarily effective, just curious). Hope this question is posed well, but let me know if it needs editing!