根据另一个列表的值顺序对字典列表进行排序

时间:2013-03-27 01:14:17

标签: python sorting python-2.7

我正在使用python 2.7.3,我正在尝试根据另一个列表的值顺序对字典列表进行排序。

IE:

listOne = ['hazel', 'blue', 'green', 'brown']
listTwo = [{'name': 'Steve', 'eyecolor': 'hazel', 'height': '5 ft. 11 inches'},
           {'name': 'Mark', 'eyecolor': 'brown', 'height': '6 ft. 2 inches'},
           {'name': 'Mike', 'eyecolor': 'blue', 'height': '6 ft. 0 inches'},
           {'name': 'Ryan', 'eyecolor': 'brown', 'height': '6 ft, 0 inches'},
           {'name': 'Amy', 'eyecolor': 'green', 'height': '5 ft, 6 inches'}]

排序listTwo基于listOne中的值的顺序,我们最终会得到以下结果:

print listTwo
[{'name': 'Steve', 'eyecolor': 'hazel', 'height': '5 ft. 11 inches'},
{'name': 'Mike', 'eyecolor': 'blue', 'height': '6 ft. 0 inches'},
{'name': 'Amy', 'eyecolor': 'green', 'height': '5 ft, 6 inches'},
{'name': 'Mark', 'eyecolor': 'brown', 'height': '6 ft. 2 inches'},
{'name': 'Ryan', 'eyecolor': 'brown', 'height': '6 ft, 0 inches'}]

我最终需要输出这个文本,所以我所做的正确显示(按照正确的顺序)如下:

for x in xrange(len(listOne)):
    for y in xrange(len(listTwo)):
        if listOne[x] == listTwo[y]["eyecolor"]:
            print "Name: " + str(listTwo[y]["name"]),
            print "Eye Color: " + str(listTwo[y]["eyecolor"]),
            print "Height: " + str(listTwo[y]["height"])

是否有某种lambda表达式可用于实现此目的?必须有一个更紧凑,更简单的方式来按我想要的顺序获取它。

1 个答案:

答案 0 :(得分:10)

最简单的方法是使用list.index为词典列表生成排序值:

listTwo.sort(key=lambda x: listOne.index(x["eyecolor"]))

这有点效率低,因为list.index通过眼睛颜色列表进行线性搜索。如果您有许多眼睛颜色要检查,那就会很慢。一种更好的方法是构建一个索引字典:

order_dict = {color: index for index, color in enumerate(listOne)}
listTwo.sort(key=lambda x: order_dict[x["eyecolor"]])

如果您不想修改listTwo,则可以使用内置的sorted功能代替list.sort方法。它返回列表的排序副本,而不是就地排序。

相关问题