按多个条件对列表进行排序并附加

时间:2014-05-01 05:42:24

标签: python list sorting python-3.x

我试图想出一种方法来同时对多个列表进行排序,然后按唯一值进行拆分并再次排序,然后展平并输出。

room_number = [100,200,300,100,400,300]
door_angle =  [ 20, 65, 118, 10, 13,50]
door =        [dr1,dr2,dr3,dr4,dr5,dr6]

我想首先按照房间号对列表进行排序,然后将它们拆分为包含重复room_number值的子列表,如下所示:

room_number = [[100,100],[200],[300,300],[400]]
door_angle = [[20,10],[65],[118,50],[13]]
door = [[dr1,dr4],[dr2],[dr3,dr6],[dr5]]

然后我想通过door_angle进一步对子列表进行排序:

room_number = [[100,100],[200],[300,300],[400]]
door_angle = [[10,20],[65],[50,118],[13]]
door = [[dr4,dr1],[dr2],[dr6,dr3],[dr5]]

我将如何解决这个问题? 先感谢您。

2 个答案:

答案 0 :(得分:3)

A = [100, 200, 300, 100, 400, 300]
B = [20, 65, 118, 10, 13, 50]
C = ['dr1', 'dr2', 'dr3', 'dr4', 'dr5', 'dr6']

print(list(map(list, map(list, A))))
# [[100, 100], [200], [300, 300], [400]]
print(list(map(list, map(list, B))))
# [[10, 20], [65], [50, 118], [13]]
print(list(map(list, map(list, C))))
# [['dr4', 'dr1'], ['dr2'], ['dr6', 'dr3'], ['dr5']]

首先,我们将zip所有值放在一起并对它们进行排序,然后根据第一个值对值进行分组。然后它只是解压缩并将数据恢复到预期的形状。

答案 1 :(得分:1)

你可以这样做。

from itertools import groupby

A = [100,200,300,100,400,300]
B = [ 20, 65, 118, 10, 13,50]
C = ['dr1', 'dr2', 'dr3', 'dr4', 'dr5', 'dr6']

grps = sorted(zip(A, B, C), key=lambda x: (x[0], x[1]))
A, B, C = [], [] ,[]
for i, grp in groupby(grps, lambda x: x[0]):
    subA, subB, subC = [], [] ,[]
    for j in grp:
        subA.append(j[0])
        subB.append(j[1])
        subC.append(j[2])
    A.append(subA)
    B.append(subB)
    C.append(subC)

输出:

>>> A
[[100, 100], [200], [300, 300], [400]]

>>> B
[[10, 20], [65], [50, 118], [13]]

>>> C
[['dr4', 'dr1'], ['dr2'], ['dr6', 'dr3'], ['dr5']]