Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic Way to Sort a List of Comma Separated Numbers

Sample Input

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

I read it in from a file as a command line argument to a list with

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

that list looks like ['20, 71146620', '100, 26867616', '10, 02513583', '10, 52811698', '100, 23859051']

My hope is to find the most pythonic way to sort this list, first for the first value and then for the second so that it looks like:

['10, 02513583', '10, 52811698', '20, 71146620', '100, 23859051', '100, 26867616', ]

I'm currently trying to convert it to a list of key value pairs, but I'm not sure that's the right direction to take.

like image 356
frankV Avatar asked Dec 21 '25 09:12

frankV


2 Answers

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)
like image 112
Petar Ivanov Avatar answered Dec 23 '25 00:12

Petar Ivanov


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

like image 24
John La Rooy Avatar answered Dec 22 '25 23:12

John La Rooy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!