2013-03-28 52 views
2

我很好奇在目前我面臨的情況下是否有優化方法。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) 

有一個更清潔的方式,我可以排序嗎?

+0

您保證每個部分只有一種顏色嗎? – jamylak 2013-03-28 09:21:27

+0

可能有更多的屬性,但它們都是引用單個字符串的唯一鍵。 – DivinusVox 2013-03-28 09:23:46

回答

3

您可以使用內置的sorted函數。

>>> lst = ['first', 'third', 'second'] 
>>> dcts = [{'color':'yellow', 'section':'third'}, {'color':'red', 'section':'first'}, {'color': 'blue', 'section':'second'}] 
>>> sorted(dcts, key=lambda dct: lst.index(dct['section'])) 
[{'section': 'first', 'color': 'red'}, {'section': 'third', 'color': 'yellow'}, {'section': 'second', 'color': 'blue'}] 
2

你可以只使用sorted()key

In [6]: o = ['first', 'third', 'second'] 

In [7]: l = [{'color':'yellow', 'section':'third'},{'color':'red', 'section':'first'}, {'color': 'blue', 'section':'second'}] 

In [8]: sorted(l, key=lambda x:o.index(x['section'])) 
Out[8]: 
[{'color': 'red', 'section': 'first'}, 
{'color': 'yellow', 'section': 'third'}, 
{'color': 'blue', 'section': 'second'}] 

這不會對o線性搜索。如果o可能很大,則應優先考慮@ jamylak的解決方案。

2

這裏是爲您提供更加優化的版本:用於排序

sort_key = lambda x: ks.index(x['section']) 

print(sorted(dicts, key=sort_key)) 
3
>>> dicts = [{'color':'yellow', 'section':'third'},{'color':'red', 'section':'first'}, {'color': 'blue', 'section':'second'}] 
>>> L = ['first', 'third', 'second'] 
>>> order = dict(zip(L, range(len(L)))) # Dictionary for O(1) lookup 
>>> sorted(dicts, key=lambda d: order[d['section']]) 
[{'color': 'red', 'section': 'first'}, {'color': 'yellow', 'section': 'third'}, {'color': 'blue', 'section': 'second'}] 

這種方法將是O(N),而不是O(N日誌N):

>>> sorted_sections = ['first', 'third', 'second'] 
>>> dicts = [{'color':'yellow', 'section':'third'},{'color':'red', 'section':'first'}, {'color': 'blue', 'section':'second'}] 
>>> dict_by_section = {d['section']:d for d in dicts} 
>>> [dict_by_section[section] for section in sorted_sections] 
[{'color': 'red', 'section': 'first'}, {'color': 'yellow', 'section': 'third'}, {'color': 'blue', 'section': 'second'}] 
+1

'.index'方法適用於小尺寸,但使用字典可以更好地縮放。 – DSM 2013-03-28 09:22:08

+0

這個「優化」有兩個問題。首先,建立一個輔助字典是O(n),其次,它需要兩倍的內存。 – georg 2013-03-28 09:57:27

+0

@ thg435我不認爲這些問題。它也不需要兩倍的內存,因爲它只存儲對每個字典的引用。 – jamylak 2013-03-28 10:03:25

0
orderList = ['first', 'third', 'second'] 
dataList = [{'color':'yellow', 'section':'third'},{'color':'red', 'section':'first'}, {'color': 'blue', 'section':'second'}] 

orderDict = dict((v,offset) for offset, v in enumerate(orderList)) 

print sorted(dataList, key=lambda d: orderDict[d['section']]) 
相關問題