How to sort a list according to another list? Python

后端 未结 4 1548
滥情空心
滥情空心 2021-01-22 09:19

So if I have one list:

name = [\'Megan\', \'Harriet\', \'Henry\', \'Beth\', \'George\']

And I have another list where each value represents the

相关标签:
4条回答
  • 2021-01-22 09:56

    You can sort them at the same time as tuples by using zip. The sorting will be by name:

    tuples = sorted(zip(name, score_list))
    

    And then

    name, score_list = [t[0] for t in tuples], [t[1] for t in tuples]
    
    0 讨论(0)
  • 2021-01-22 10:03

    One obvious approach would be to zip both the list sort it and then unzip it

    >>> name, score = zip(*sorted(zip(name, score_list)))
    >>> name
    ('Beth', 'George', 'Harriet', 'Henry', 'Megan')
    >>> score
    (6, 10, 6, 5, 9)
    
    0 讨论(0)
  • 2021-01-22 10:03

    Consider a third-party tool more_itertools.sort_together:

    Given

    import more_itertools as mit
    
    
    name = ["Megan", "Harriet", "Henry", "Beth", "George"]
    score_list = [9, 6, 5, 6, 10]
    

    Code

    mit.sort_together([name, score_list])
    # [('Beth', 'George', 'Harriet', 'Henry', 'Megan'), (6, 10, 6, 5, 9)]
    

    Install more_itertools via > pip install more_itertools.

    0 讨论(0)
  • 2021-01-22 10:18

    The correct way if you have a dict is to sort the items by the key:

    name = ['Megan', 'Harriet', 'Henry', 'Beth', 'George']
    
    score_list = [9, 6, 5, 6, 10]
    d = dict(zip(name, score_list))
    
    from operator import itemgetter
    print(sorted(d.items(), key=itemgetter(0)))
    [('Beth', 6), ('George', 10), ('Harriet', 6), ('Henry', 5), ('Megan', 9)]
    
    0 讨论(0)
提交回复
热议问题