我很好奇在目前我面臨的情況下是否有優化方法。Python:使用另一個列表作爲訂單對列表進行排序
我有表示由類別,以便和訂單數據字符串的列表:
['first', 'third', 'second']
這對應於含有那些需要類別的對象類型的字典的列表進行排序,根據它們:
[{'color':'yellow', 'section':'third'},{'color':'red', 'section':'first'}, {'color': 'blue', 'section':'second'}]
數據列表應經由所述第一組中給定的順序進行排序,在這種情況下產生:
[{'color':'red', 'section':'first'},{'color':'yellow', 'section':'third'},{'color': 'blue', 'section':'second'}]
我目前的解決方案:
sortedList = []
for section in orderList:
for item in dataList:
if item['section'] == section: sortedList.append(item)
有一個更清潔的方式,我可以排序嗎?
您保證每個部分只有一種顏色嗎? – jamylak 2013-03-28 09:21:27
可能有更多的屬性,但它們都是引用單個字符串的唯一鍵。 – DivinusVox 2013-03-28 09:23:46