簡體   English   中英

根據另一個列表的值順序對字典列表進行排序

[英]Sorting a list of dictionaries based on the order of values of another list

我正在使用 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'}]

根據 listOne 中值的順序對 listTwo 進行排序,我們將得到以下結果:

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 表達式可用於實現這一目標? 必須有一種更緊湊、更簡單的方式來按我想要的順序獲取它。

最簡單的方法是使用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方法。 它返回列表的排序副本,而不是就地排序。

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'}]


order_list_dict = {color: index for index, color in enumerate(listOne)}


print(order_list_dict)

print(sorted(listTwo, key=lambda i: order_list_dict[i["eyecolor"]]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM