Sorting Scientific Number With Unix Sort

后端 未结 4 1753
面向向阳花
面向向阳花 2021-02-02 12:12

I tried to sort these number with Unix sort, but it doesn\'t seem to work:

    2e-13
    1e-91
    2e-13
    1e-104
    3e-19
    9e-99

This is

4条回答
  •  粉色の甜心
    2021-02-02 12:47

    Ok, here is a not fully tested version of Python script. Supposed usage:

    sort_script.py file.txt
    

    Unfortunately I developed this on Windows, and with 2 different versions of Python installed I cannot test it properly. Warning: requires newest Python (with, print functions added or changed). Note: back_to_file flag can be an optional parameter, although with Unix you can always redirect ... even in Windows you can.

    #!/usr/bin/env python3.1
    # Note: requires newer python
    
    import sys
    
    #Remove this line:
    sys.argv = ('', 'file.txt')
    
    assert(len(sys.argv) == 2)
    
    with open(sys.argv[1], 'r') as fin:
        lines = fin.readlines()
    
    lines_sorted = sorted(lines, key=lambda x: float(x))
    
    back_to_file = False # Change this if needed
    
    if back_to_file:
        with open(sys.argv[1], 'w') as fout:
            fout.writelines(lines_sorted)
    else:
        for lns in lines_sorted:
            print(lns, end='') # Suppress new line
    

提交回复
热议问题