Sorting list of lists by a third list of specified non-sorted order

前端 未结 3 1409
我寻月下人不归
我寻月下人不归 2021-01-06 06:18

I have a list:

[[\'18411971\', \'kinase_2\', 36], [\'75910712\', \'unnamed...\', 160], ...
  • about 60 entries long
  • each entry
3条回答
  •  庸人自扰
    2021-01-06 06:52

    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']]
    

提交回复
热议问题