如何从字典值中排序列表

时间:2018-03-24 19:05:55

标签: python python-2.7 sorting dictionary

我有一个从Dijkstra算法生成的路径列表,需要创建另一个列表来指示路径的位置,我已经有了正确的输出,但顺序不同,我的输入顺序与我的顺序相同。

boardPos   = [['F0','F1','F2','F3','F4'],
              ['E0','E1','E2','E3','E4'],
              ['D0','D1','D2','D3','D4'],
              ['C0','C1','C2','C3','C4'],
              ['B0','B1','B2','B3','B4'],
              ['A0','A1','A2','A3','A4']]

dijkstra = ['A2', 'B2', 'B1', 'B0', 'C0']

pos2Coord ={}
coordList = []

for iRow in range(len(boardPos)):
    for iCol in range(len(boardPos[iRow])):
        pos2Coord.update({boardPos[iRow][iCol] : (iRow, iCol)})

print (pos2Coord.items())
coordDict = {pk:pv for pk,pv in pos2Coord.items() if pk in dijkstra}
coordList = coordDict.values()
print (coordList)

输出:

pos2Coord:
[('D1', (2, 1)), ('A4', (5, 4)), ('A1', (5, 1)), ('E4', (1, 4)), ('B1', (4, 1)), 
 ('D4', (2, 4)), ('F0', (0, 0)), ('F1', (0, 1)), ('F2', (0, 2)), ('F3', (0, 3)), 
 ('F4', (0, 4)), ('E2', (1, 2)), ('E1', (1, 1)), ('E0', (1, 0)), ('B4', (4, 4)), 
 ('A0', (5, 0)), ('A3', (5, 3)), ('A2', (5, 2)), ('B0', (4, 0)), ('E3', (1, 3)), 
 ('B2', (4, 2)), ('B3', (4, 3)), ('C3', (3, 3)), ('C2', (3, 2)), ('C1', (3, 1)), 
 ('C0', (3, 0)), ('D2', (2, 2)), ('D3', (2, 3)), ('D0', (2, 0)), ('C4',(3, 4))]

coordList:
[(3, 0), (5, 2), (4, 0), (4, 1), (4, 2)]

我需要的顺序与Dijkstra的位置相同:

#['A2', 'B2', 'B1', 'B0', 'C0']    
[(5, 2), (4, 2), (4, 1), (4, 0), (3, 0)]

1 个答案:

答案 0 :(得分:2)

这是一种方式。

res = sorted(coordDict.items(), key=lambda x: dijkstra.index(x[0]))
# [('A2', (5, 2)), ('B2', (4, 2)), ('B1', (4, 1)), ('B0', (4, 0)), ('C0', (3, 0))]

res_values = list(list(zip(*res))[1])
# [(5, 2), (4, 2), (4, 1), (4, 0), (3, 0)]

<强>解释

  • sorted接受一个key参数,该参数接受匿名(lambda)函数。
  • 在字典项上使用sorted,对字典键的dijkstra索引级别进行排序。
  • sorted的结果是按要求排序的元组列表。
  • 对于res_values,请在通过zip(*res)解压后选择第二个元素来解压缩值。