Python unusual file sorting -


i have txt file contains data in following fashion:

23       1      65      15      19.2 19       2      66      25      25.7 10       3      67      35      16.5 100      4      68      45      10.4 20       5      69      55      6.8 201      6      64      65      9.2 

within file, each value separated other using \t , \n next line.

i want sort file based on first values of each line. expected output :

10       3      67      35      16.5 19       2      66      25      25.7 20       5      69      55      6.8 23       1      65      15      19.2 100      4      68      45      10.4 201      6      64      65      9.2 

but actual output getting as:

10       3      67      35      16.5 100      4      68      45      10.4 19       2      66      25      25.7 20       5      69      55      6.8 201      6      64      65      9.2 23       1      65      15      19.2 

its taking values strings , hence not taking entire numbers value integer. tried parsing, not working.

my code:

with open('filename.txt') fin:         lines = [line.split() line in fin] lines.sort(key=itemgetter(0),reverse=true)  open('newfile.txt', 'w') fout:     in lines:             fout.write('{0}\t\t\t\t\n'.format('\t\t\t '.join(i))) 

please if possible.

you're comparing strings, need compare integers:

lines.sort(key=lambda x:int(x[0]), reverse=true) 

strings compared lexicographically, so:

>>> '2' > '100' true 

conversion int fixes issue:

>>> int('2') > int('100') false 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -