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

标签 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)

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

最佳答案

您可以使用内置的 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/

相关文章:

ruby - 在 ruby​​ 中按批处理对数组进行排序

C++ 标准列表使用自定义比较器排序,该比较器取决于对象实例的成员变量

Python请求很慢,并且需要很长时间才能完成HTTP或HTTPS请求

python - 带外键的 Django 表单

python - 如何在python中获取矩阵?

python - 删除 PANDAS 中的第二行标题

nhibernate - 如何在 (n)hibernate 中对子对象的属性进行排序?

python - pymodbus解码错误: [Input/Output] No response received from the remote unit/Unable to decode response

javascript - 快速排序没有输出

python - 列表列表中不同元素的不同顺序排序