Pythonic Way to Sort a List of Comma Separated Numbers

后端 未结 4 1543
不思量自难忘°
不思量自难忘° 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: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

提交回复
热议问题