Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file read and for loop in python

I have this file:

-0
1
16
9
-00
1
3
4
0
7
9
-000
...

and I want to sort them and store them to a file.

I read the file store them inside a list , sort the list and then save the list to a file. Problem is that It starts from the second -x .

 for line in file:
        temp_buffer = line.split()
        for i,word in enumerate(temp_buffer):
            if "-" not in word:
                if word in index_dict:
                    l1.append(word)
                else:
                    l1.append(function(word))
            else:
                l1.append(word)
                l1.sort()
                print(l1 , file=testfile)
                del l1
                l1 = []

So the 1st loop it goes to the else statment and stores just the first -0 without the words beween -0 and -00. How should I fix this ? I want the output to be like that :

-0
1
9
16
-00
0
1
3
4
7
9
-000
....
like image 666
bill Avatar asked Jul 26 '26 01:07

bill


1 Answers

You can use itertools.groupby to "partition" the data into groups between lines starting with - instead. Where it starts with - write the line out, otherwise, write the sorted lines, eg:

from itertools import groupby

with open('input') as fin, open('output', 'w') as fout:
  for k, g in groupby(fin, lambda L: L.startswith('-')):
    if k:
      fout.writelines(g)
    else:
      fout.writelines(sorted(g, key=int))
like image 78
Jon Clements Avatar answered Jul 27 '26 15:07

Jon Clements