I have a 2D list having many elements and row of different length. Let's call it ListA. I order listA like this:
listA.sort(key=len)
I have another 2D list ( listB
) which I would like to sort like A is sorted. If row 3 of A becomes the first row, the third row of B must go first and so on.
How can I do?
I don't want to use numpy.
EDIT: I try to be more clear:
Suppose a matrix A made like this (The original matrix is a lot bigger)
A = [
[
[86,98,98,0,0]
],
[
[79,71,105,1,1], [79,71,106,1,1], [80,72,105,0,2]
],
[
[86,81,27,1,1], [85,80,25,1,0]
],
[
[99,80,73,1,1], [99,81,73,2,1]
]
]
this matrix has 4 rows with different length (1, 3, 2, 2). Actually each length contains the coordinates and other values of my analysis. I want to order A so that first I have the shortest row and at the end the longest one. In this case (1, 2, 2, 3)
Now I also have another matrix B which has the same number of rows as A but might have different length compared to A.
B = [
[
[8,79,3],[8,77,42]
],
[
[10,83,70]
],
[
[9,81,74], [13,67,43], [4,15,88]
],
[
[5,14,88]
]
]
I want to sort the rows of B to correspond the sorted rows in A.
This is how i would go about doing it:
a = ['easd', 'sdvgweag', '21x', 'npasp oopp agt']
b = [42, 7642, 2146, 12]
temp = list(zip(a, range(len(a))))
temp.sort(key=lambda x: len(x[0]))
a.sort(key=len)
print(a) # ['21x', 'easd', 'sdvgweag', 'npasp oopp agt']
print([b[i] for i in [x[1] for x in temp]]) # [2146, 42, 7642, 12]
The idea behind this is to add some mechanism of tracking the changes in list a
. This is what zip()
does.
With the updated question your problem is much clear now.
You can use a similar logic to my previous answer.
A=[[[86,98,98,0,0]],[[79,71,105,1,1],[79,71,106,1,1],[80,72,105,0,2]], [[86,81,27,1,1],[85,80,25,1,0]], [[99,80,73,1,1],[99,81,73,2,1]]]
B=[[[8,79,3],[8,77,42]],[[10,83,70]],[[9,81,74],[13,67,43],[4,15,88]],[[5,14,88]]]
#check the length of each row and pair it into a new array
tempA = [] # array
for index in range(len(A)):
itemLength = len(A[index])
tempA.append([itemLength,index, A[index]])
tempB = {} #dict
for index in range(len(B)):
tempB[index] = B[index]
# sort tempA according to row length
tempA.sort()
B = []
A = []
for item in tempA:
indexBeforeSorting = item[1]
B.append(tempB[indexBeforeSorting])
A.append( item[2])
This works perfectly
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.