Python:如何根据另一个list_of_lists对list_of_lists进行排序? [英] Python: How to sort a list_of_lists based on another list_of_lists?

查看:57
本文介绍了Python:如何根据另一个list_of_lists对list_of_lists进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我要解决的用例:

Below is the use-case I am trying to solve:

我有2个列表列表:( l d )

I have 2 lists of lists: (l and d)

In [1197]: l
Out[1197]: 
[['Cancer A', 'Ecog 9', 'Fill 6'],
 ['Cancer B', 'Ecog 1', 'Fill 1'],
 ['Cancer A', 'Ecog 0', 'Fill 0']]

In [1198]: d
Out[1198]: [[100], [200], [500]]

这是一个两部分的问题:

It's a 2-part problem here:

  1. 根据值的优先级对 l 进行排序.例如: Cancer Ecog Fill (在这种情况下为 key =(0,1,2)).可能是 Ecog Cancer Fill 之类的东西,因此,key =(1,0,2).
  2. l 在步骤上方被依次排序的相同顺序对 d 进行排序.
  1. Sort l based on the priority of values. eg: Cancer, Ecog and Fill (in this case key=(0,1,2)). It could be anything like Ecog, Cancer, Fill so, key=(1,0,2).
  2. Sort d in the same order in which l has been sorted int above step.

我能够实现的第1步,如下所示:

Step #1 I'm able to achieve, like below:

In [1199]: import operator
In [1200]: sorted_l = sorted(l, key=operator.itemgetter(0,1,2))

In [1201]: sorted_l
Out[1200]: 
[['Cancer A', 'Ecog 0', 'Fill 0'],
 ['Cancer A', 'Ecog 9', 'Fill 6'],
 ['Cancer B', 'Ecog 1', 'Fill 1']]

现在,我想以与 sorted_l 相同的顺序对 d 的值进行排序.

Now, I want to sort values of d in the same order as the sorted_l.

预期输出:

In [1201]: d
Out[1201]: [[500], [100], [200]]

做到这一点的最佳方法是什么?

What is the best way to do this?

推荐答案

下面是@ juanpa.arrivillaga的帮助下的解决方案:

Below is the solution with help from @juanpa.arrivillaga :

In [1272]: import operator
In [1273]: key = operator.itemgetter(0, 1, 2)

# Here param key, lets you sort `l` with your own function.
In [1275]: sorted_l,sorted_d = zip(*sorted(zip(l, d), key=lambda x: key(x[0])))

In [1276]: sorted_l
Out[1276]: 
(['Cancer A', 'Ecog 0', 'Fill 0'],
 ['Cancer A', 'Ecog 9', 'Fill 6'],
 ['Cancer B', 'Ecog 1', 'Fill 1'])

In [1277]: sorted_d
Out[1277]: ([500], [100], [200])

这篇关于Python:如何根据另一个list_of_lists对list_of_lists进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆