如何按照我想要的顺序对多维列表进行自定义排序? (不使用任何外部模块或库)
例如,我有一个多维列表:
[['M', 'A', 'R', 'K']
[1, 3, 5, 4]
[2, 6, 7, 8]]
我想将其列排序为 R、K、A、M 顺序,例如:
[['R', 'K', 'A', 'M']
[5, 4, 3, 1]
[7, 8, 6, 2]]
我只知道如何使用这段代码按字母顺序对列表进行排序:
sorted_l = [i for i in zip(*sorted(zip(*l)))]
生成以下结果:
[['A', 'K', 'M', 'R']
[3, 4, 1, 5]
[6, 8, 2, 7]]
谢谢!
最佳答案
l= [['M', 'A', 'R', 'K'],[1, 3, 5, 4],[2, 6, 7, 8]]
inds = "RKAM"
print(sorted(zip(*l),key=lambda x: inds.index(x[0])))
[('R', 5, 7), ('K', 4, 8), ('A', 3, 6), ('M', 1, 2)]
print(zip(*sorted(zip(*l),key=lambda x: inds.index(x[0]))))
[('R', 'K', 'A', 'M'), (5, 4, 3, 1), (7, 8, 6, 2)]In [6]: trans =
In [6]: trans = sorted(zip(*l),key=lambda x: inds.index(x[0]))
In [7]: trans[0] # each 0 in inds.index(x[0]) is either R,K, A or M
Out[7]: ('R', 5, 7)
In [8]: trans[1]
Out[8]: ('K', 4, 8)
In [9]: trans[2]
Out[9]: ('A', 3, 6)
In [10]: trans[3]
Out[10]: ('M', 1, 2)
In [11]: zip(*trans) # finally transpose sorted columns again
Out[11]: [('R', 'K', 'A', 'M'), (5, 4, 3, 1), (7, 8, 6, 2)]
关于python - 如何在 Python 中使用给定标签自定义排序多维列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27369637/