2

我很好奇是否有办法在我目前面临的情况下进行优化。

我有一个代表类别的字符串列表,通过以下方式对数据进行分组和排序:

['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)

有没有更清洁的方法可以排序?

4

5 回答 5

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'}]
于 2013-03-28T09:18:29.320 回答
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 log 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'}]
于 2013-03-28T09:19:33.460 回答
2

您可以只使用sorted()with 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 的解决方案。

于 2013-03-28T09:18:09.203 回答
2

这是一个更优化的版本:

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

print(sorted(dicts, key=sort_key))
于 2013-03-28T09:18:32.187 回答
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']])
于 2013-03-28T09:26:41.780 回答