在Python中对3个列表进行排序的更优雅方法

时间:2014-06-04 01:34:47

标签: python list

我有3个列表,我想对列表进行排序" relative"彼此(例如,将每个列表描绘为3x3矩阵中的行,我想按列对其进行排序)。

我想知道是否有更优雅的方式来做到这一点。我想出的是使用临时列表,下面是一个简化的例子:

list1 = ['c','b','a']
list2 = [6,5,4]
list3 = ['some-val-associated-with-c','another_value-b','z_another_third_value-a']


tmp, list2 = (list(x) for x in zip(*sorted(zip(list1, list2), key=lambda pair: pair[0])))
list1, list3 = (list(x) for x in zip(*sorted(zip(list1, list3), key=lambda pair: pair[0])))

print(list1, '\n', list2, '\n', list3)

[1, 2, 3] [4, 5, 6] ['a', 'b', 'c']

输出(实际和期望的输出):

['a', 'b', 'c'] 
 [4, 5, 6] 
 ['z_another_third_value-a', 'another_value-b', 'some-val-associated-with-c']

而我不想要的是:

 ['a', 'b', 'c'] 
 [4, 5, 6] 
 ['another_value-b', 'some-val-associated-with-c', 'z_another_third_value-a']

1 个答案:

答案 0 :(得分:3)

list1, list2, list3 = zip(*sorted(zip(list1, list2, list3)))
相关问题