按指定的非排序顺序的第三个列表对列表进行排序 [英] Sorting list of lists by a third list of specified non-sorted order

查看:77
本文介绍了按指定的非排序顺序的第三个列表对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表:

[['18411971', 'kinase_2', 36], ['75910712', 'unnamed...', 160], ...

  • 大约60个条目
  • 每个条目都是一个包含三个值的列表
  • 我想按第一个值对这个较大的列表进行排序,该值由另一个按所需顺序排列的列表指定.

    I want to sort this bigger list by the first value in an order specified by another list which has them in the desired order.

    推荐答案

    通常的习惯用法是使用键进行排序:

    The usual idiom is to sort using a key:

    >>> a = [[1,2],[2,10,10],[3,4,'fred']]
    >>> b = [2,1,3]
    >>> sorted(a,key=lambda x: b.index(x[0]))
    [[2, 10, 10], [1, 2], [3, 4, 'fred']]
    

    但是,这可能会导致性能问题-如果键是可哈希的,则对于长列表来说,这可能会更快:

    This can have performance issues, though-- if the keys are hashable, this will probably be faster for long lists:

    >>> order_dict = dict(zip(b, range(len(b))))
    >>> sorted(a,key=lambda x: order_dict[x[0]])
    [[2, 10, 10], [1, 2], [3, 4, 'fred']]
    

    这篇关于按指定的非排序顺序的第三个列表对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆