重新排序列表以匹配另一个

时间:2015-10-07 13:52:25

标签: python list

说我有一个类似的数组:

[[1356, a], [478, b], [60, c], [61, d]]

是否可以重新排序以匹配数组:

[d, b, a, c]

像:

[[61,d], [478,b], [1356,a], [60,c]]

我想要的订单位于csv文件的第二列。所以我有:

with open('data.csv', "r") as csvfile:
     order = csv.reader(csvfile, delimiter = ',')
     code_order=[]
     for row in order:
        code_order.append(row[2])
     reordered_output=[]
     for i,x  in enumerate(code_order):
          where x[i] in result
               reordered_ouput[i] = result
     print(reordered_output)

1 个答案:

答案 0 :(得分:7)

其中一种方法是将sortedkey

一起使用
>>> a = [[1356, 'a'], [478, 'b'], [60, 'c'], [61, 'd']]
>>> b = ['d', 'b', 'a', 'c']
>>> sorted(a, key = lambda x : b.index(x[1]))
[[61, 'd'], [478, 'b'], [1356, 'a'], [60, 'c']]