sorting multiple lists based on a single list in python

前端 未结 3 1537
忘掉有多难
忘掉有多难 2021-01-02 00:58

I\'m printing a few lists but the values are not sorted.

for f, h, u, ue, b, be, p, pe, m, me in zip(filename, human_rating, rating_unigram, percentage_error         


        
相关标签:
3条回答
  • 2021-01-02 01:44

    How about this: zip into a list of tuples, sort the list of tuples, then "unzip"?

    l = zip(filename, human_rating, ...)
    l.sort()
    # 'unzip'
    filename, human_rating ... = zip(*l)
    

    Or in one line:

    filename, human_rating, ... = zip(*sorted(zip(filename, human_rating, ...)))
    

    Sample run:

    foo = ["c", "b", "a"]
    bar = [1, 2, 3]
    foo, bar = zip(*sorted(zip(foo, bar)))
    print foo, "|", bar # prints ('a', 'b', 'c') | (3, 2, 1)
    
    0 讨论(0)
  • 2021-01-02 01:46

    I would zip then sort:

    zipped = zip(filename, human_rating, …)
    zipped.sort()
    for row in zipped:
         print "{:>6s}{:>5.1f}…".format(*row)
    

    If you really want to get the individual lists back, I would sort them as above, then unzip them:

    filename, human_rating, … = zip(*zipped)
    
    0 讨论(0)
  • 2021-01-02 01:47

    zip returns a list of tuples which you can sort by their first value. So:

    for ... in sorted(zip( ... )):
        print " ... "
    
    0 讨论(0)
提交回复
热议问题