[英]Sort 2D list based on how I sort another 2D list rows with Python
我有一個2D列表,其中包含許多元素和不同長度的行。 我們稱之為ListA。 我訂購listA像這樣:
listA.sort(key=len)
我還有另一個2D列表( listB
),我想對其進行排序,就像對A進行排序一樣。 如果A的第3行成為第一行,則B的第三行必須排在第一位,依此類推。
我能怎么做?
我不想使用numpy。
編輯:我試圖更加清楚:
假設這樣制作的矩陣A(原始矩陣大很多)
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]
]
]
此矩陣有4行,其長度不同(1、3、2、2)。 實際上,每個長度都包含我的分析的坐標和其他值。 我想訂購A,以便首先我擁有最短的一排,最后我擁有最長的一排。 在這種情況下(1、2、2、3)
現在,我還有另一個矩陣B,它的行數與A相同,但與A的長度可能不同。
B = [
[
[8,79,3],[8,77,42]
],
[
[10,83,70]
],
[
[9,81,74], [13,67,43], [4,15,88]
],
[
[5,14,88]
]
]
我想對B的行進行排序以對應於A中的排序行。
這就是我要做的事情:
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]
其背后的想法是添加一些機制來跟蹤列表a
的更改。 這就是zip()
所做的。
有了更新的問題,您的問題現在已經很清楚了。
您可以使用與我之前的答案類似的邏輯。
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])
這完美地工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.