【问题标题】:Sorting list of lists based on another list of lists根据另一个列表列表对列表列表进行排序
【发布时间】:2021-05-02 07:50:38
【问题描述】:

我有一个列表列表,我想按照与另一个列表列表相同的顺序进行排序:

l1 = [['hello', 'test'], ['there', 'correct'], ['Elem3', 'yes']]

l2 = [['hello'], ['Elem3'], ['there']]

所以我想重新排列 l1 使其与 l2 的顺序相同。 (注意:这只是一个简单的测试用例。我正在处理的实际列表中有几个元素。

例如结果应该是:

l1 = [['hello', 'test'], ['Elem3', 'yes'], ['there', 'correct']]

使用python2(企业版)

【问题讨论】:

    标签: python sorting python-2.x


    【解决方案1】:

    使用python内置的sort

    l1.sort(key=lambda pair: l2.index(pair[0]))
    

    【讨论】:

      【解决方案2】:

      这不是很漂亮或高效,但我认为这些不是要求:

      >>> l3 = [None] * len(l2)
      >>> for item in l1:
      ...     l3[l2.index([item[0]])] = item
      >>> print l3
      [['hello', 'test'], ['Elem3', 'yes'], ['there', 'correct']]
      

      【讨论】:

        猜你喜欢
        • 2018-11-15
        • 2013-09-17
        • 1970-01-01
        • 2011-03-22
        • 2023-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多