我很好奇是否有一种方法可以优化我目前面临的情况。
我有一个表示类别的字符串列表,用于对数据进行分组和排序:
['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)
有没有更简洁的方法可以对此进行排序?
最佳答案
您可以使用内置的 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'}]
关于Python:使用另一个列表作为顺序对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15678004/