pythonredirectstandardoutput

any easy way to sort the standard out by the float number in descending order in python?


I have a standard output like below:

seventy-five 0.050
states 0.719
drainage-basin 0.037
scotland 0.037
reading 0.123
thirty-eight 0.000
almost 0.037
rhine 0.000
proper 0.037
contrary 0.087

Any easy way to sort the long standard output list based on the float number at the back in order of descending value and keep the standard output format instead of converting it to list and sort? Sorry for the silly question as I am a beginner of python.


Solution

  • Sorting with a list seems pretty natural. You sort lines (data.split('\n')) by the float value at the end of each line (float(line.split()[-1]) and obtain a descending order with the reverse keyword.

    data = """seventy-five 0.050
    states 0.719
    drainage-basin 0.037
    scotland 0.037
    reading 0.123
    thirty-eight 0.000
    almost 0.037
    rhine 0.000
    proper 0.037
    contrary 0.087"""
    
    result = "\n".join(
        sorted(data.split("\n"), key=lambda s: float(s.split()[-1]), reverse=True)
    )
    
    print(result)
    
    # states 0.719
    # reading 0.123
    # contrary 0.087
    # seventy-five 0.050
    # drainage-basin 0.037
    # scotland 0.037
    # almost 0.037
    # proper 0.037
    # thirty-eight 0.000
    # rhine 0.000
    

    If you have list-aversion you could use command line tools like sort.