I have a small question. I have a file in the following format:
1 2
1 2 3
1 2
1 2 3 4
2 4
The values in the code actually represent numbers(not necessarily single digit), but they can be any number, can be floating point values too.
Input file: For a particular row, each number is separated from another by a single whitespace (the separator can’t be anything other than whitespace).
My task: I want to zero fill the empty spaces in such a way that it looks like this, i.e. fill up the empty spaces in such a way that it gives me a nice matrix-looking format:
1 2 0 0
1 2 3 0
1 2 0 0
1 2 3 4
2 4 0 0
Output file: Same rule applies. For a particular row, each number is separated from another by a single whitespace only.
Language used: Python(or may be Shell, if that’s possible)
I know there is this function called zfill, but I don’t think that would be much of a help to me.
My solution: Find the (maximum length/2) of each line, using len and max functions. Then, using split(), fill up with zeros at appropriate places of each line. I am afraid it might turn into a dirty code and I’m sure there are better ways to accomplish this task.
Any suggestion is welcome.
Thank you!
Assume
myfileis the open file. We use izip_longest from itertools to iterate over the columns of the input file, filling in"0"for missing values:Then we simply zip this output again to restore the rows with zeroes filled in. This is the code:
EDIT: The above (imho elegant) solution is slightly slower (8.55 usec vs. 7.08 usec) than the naive approach:
Re: comment
If you want to align the columns it’s easiest to amend the first approach, because there we already have the numbers arranged by column at one point. That makes finding the column width easy.