Pythonic Way to Sort a List of Comma Separated Numbers

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

提交回复
热议问题