Python:使用另一个列表作为订单对列表进行排序

时间:2013-03-28 09:15:04

标签: python sorting

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

我有一个字符串列表,表示按组分组和订购数据的类别:

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

有没有更简洁的方法可以对此进行排序?

5 个答案:

答案 0 :(得分: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'}]

答案 1 :(得分: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'}]

答案 2 :(得分: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的解决方案应该是首选。

答案 3 :(得分:2)

这是一个更优化的版本:

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

print(sorted(dicts, key=sort_key))

答案 4 :(得分: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']])