[英]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.