Pythonic Way to Sort a List of Comma Separated Numbers

后端 未结 4 1548
不思量自难忘°
不思量自难忘° 2021-01-20 11:25

Sample Input

20, 71146620
100, 26867616
10, 02513583
10, 52811698
100, 23859051

I read it in from a file as a command line

相关标签:
4条回答
  • 2021-01-20 11:38

    The easiest thing to do is to parse the pairs into lists and then just sort them:

    lin = [i.strip().split(', ') for i in open(sys.argv[1]).readlines()]
    lin = sorted(lin)
    

    In case you want to sort numerically, just cast to numbers:

    lin = [map(int, i.strip().split(', ')) for i in open(sys.argv[1]).readlines()]
    lin = sorted(lin)
    
    0 讨论(0)
  • 2021-01-20 11:41
    import sys
    with open(sys.argv[1]) as f:
        lin = sorted([[int(j) for j in i.split(",")] for i in f])
    print lin
    
    0 讨论(0)
  • 2021-01-20 11:42

    why not just use the csv module and feed it to sort (with a string to integer conversion)

    import csv
    
    with open("test.csv") as f:
        cr = csv.reader(f)
        result = sorted(list(map(int,row)) for row in cr)
    

    outcome:

    >>> result
    [[10, 2513583],
     [10, 52811698],
     [20, 71146620],
     [100, 23859051],
     [100, 26867616]]
    

    sort does exactly what's asked here: it uses natural sorting order of lists

    0 讨论(0)
  • 2021-01-20 11:53

    You can sort the lines as strings, by using a key function

    def two_ints(s):
        return map(int, s.split(","))
    
    with open("num.txt") as f:
        for line in sorted(f, key=two_ints):
            print line
    

    It really depends whether you want the result to be a list of strings, or a list of lists of ints.

    Once you have converted to int, there is no way to recover the leading zero on "02513583", so leaving the result as strings may be preferable

    0 讨论(0)
提交回复
热议问题