【问题标题】:Pythonic way: Sort array items based on a class member and another arrayPythonic 方式:基于类成员和另一个数组对数组项进行排序
【发布时间】:2013-04-18 15:17:57
【问题描述】:

我已经尝试了所有我能想象的,但似乎无法得出一个有效的解决方案。

我需要根据 ID 对一组类对象进行排序,以便该 ID 与另一个列表中的 ID 相同。

class Item:
  def __init__(self,i):
    self.i = i

itemList = [Item(2),Item(1),Item(4),Item(3)]
indexList = [3,1,2,4]

预期输出:

itemList_sorted = [Item(3), Item(1), Item(2), Item(4)]

我看到了一个类似的强烈反对的问题here,但该解决方案对我没有帮助,因为我无法使用函数并且需要将每个项目的成员与另一个数组中的索引进行比较。

itemList.sort(key=lambda x: x.i - indexList.index) # Wrong
itemList.sort(key=indexList.index,cmp=lambda x,y: x.i==y) # Wrong

有没有一种 Pythonic 方法可以在不使用类 C 循环的情况下完成此操作?

提前感谢您的帮助!

【问题讨论】:

    标签: python arrays sorting


    【解决方案1】:

    使用sorted(..., key):

    sorted(itemList, key=lambda item: indexList.index(item.i))
    

    【讨论】:

    • 太快了!真的谢谢!
    【解决方案2】:

    如果您可以假设 indexlist 中的每个索引都是您的 Items 的 i,那么您可以作弊并按顺序创建它们:

    itemList = [Item(i) for i in indexList]
    

    如果这不是一个选项,您可以排序:

    itemList.sort(key=lambda x: indexList.index(x.i))
    

    【讨论】:

      【解决方案3】:

      其他答案解决了如何正确进行排序-但我觉得您在这里采用了错误的方法。为什么不直接建立一个新列表而不是尝试对旧列表进行排序?

      [next(y for y in itemList if y.i == x) for x in indexList]
      

      请注意,这实际上应该比使用 sort 更快,后者必须为每个 O(n log n) 比较搜索一次 indexList

      【讨论】:

      • 这是一个非常pythonic的解决方案!
      • @kojiro 的答案中的第一个选项实际上更适合您的具体示例,但我假设您的 Item 课程实际上比这更复杂,因此无法仅根据以下内容重建项目indexList.
      • 是的,我的课是一个复杂的结构。我选择了您的答案,因为它具有更大的灵活性并且仍然非常易读。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-03
      • 2017-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-08
      相关资源
      最近更新 更多