python - 如何在 Python 中使用给定标签自定义排序多维列表

标签 python algorithm list sorting multidimensional-array

如何按照我想要的顺序对多维列表进行自定义排序? (不使用任何外部模块或库)

例如,我有一个多维列表:

[['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/

相关文章:

python - 消息从本地 python 传递到 chrome 扩展

c++ - 如何将 for 循环变成数学方程式?

list - Prolog:不带累加器的最大值谓词

list - Scala 中用于列表减法的 "--"运算符

python - 我如何在python中按值分配

python - 如何使用 SQLAlchemy 重新插入一行?

python - 如何在 Django Rest 框架中设置 View

python - 如何创建具有特定服务帐户设置的 Google Compute Engine 实例?

algorithm - 找到达到一定总和的最小迭代次数

javascript - 如何以对数时间检查具有相等值的对象是否在容器中