2013-03-28 47 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']]) 
相关问题