根据另一个列表的值顺序对字典列表进行排序
我正在使用python 2.7.3,并且试图根据另一个列表的值顺序对字典列表进行排序.
I'm using python 2.7.3, and I'm trying to sort a list of dictionaries based on the order of values of another list.
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'}]
根据listOne中值的顺序对listTwo进行排序,我们将得到以下结果:
Sorting listTwo based off of the order of values in listOne, we would end up with the following:
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'}]
我最终需要输出此文本,因此我为正确显示(以正确的顺序)所做的事情如下:
I eventually need to output this text, so what I've done to display it correctly (in the correct order) is the following:
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表达式?必须有一种更紧凑,更简单的方法来按我想要的顺序来获取它.
Is there some sort of lambda expression that can be used to make this happen? There has to be a more compact, less complex way of getting it in the order I want.
最简单的方法是使用list.index
为词典列表生成排序值:
The simplest way would be to use list.index
to generate a sort value for your list of dictionaries:
listTwo.sort(key=lambda x: listOne.index(x["eyecolor"]))
但这有点效率低下,因为list.index
在眼睛颜色列表中进行了线性搜索.如果您要检查的眼睛颜色很多,那将会很慢.更好的方法是改为建立索引字典:
This is a little bit inefficient though, since list.index
does a linear search through the eye-color list. If you had many eye colors to check against, it would be slow. A somewhat better approach would build an index dictionary instead:
order_dict = {color: index for index, color in enumerate(listOne)}
listTwo.sort(key=lambda x: order_dict[x["eyecolor"]])
如果不想修改listTwo
,则可以使用内置的sorted
函数而不是list.sort
方法.它返回列表的排序副本,而不是就地排序.
If you don't want to modify listTwo
, you can use the built-in sorted
function instead of the list.sort
method. It returns a sorted copy of the list, rather than sorting in-place.