Zero fills empty spaces in certain places

I have a little 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 a single digit), but they can be any number, they can also be floating point values.

Input file: for a certain line, each number is separated from the other by one space (the delimiter cannot be something other than a space).

My task: I want the zero to fill the empty spaces so that it looks like that is, to fill the empty spaces so that it gives me a beautiful matrix format:

1 2 0 0
1 2 3 0
1 2 0 0
1 2 3 4
2 4 0 0

Output file: the same rule applies. For a particular line, each number is separated from the other by only one space.

Used language: Python (or maybe Shell, if possible)

, zfill, , .

: ( /2) , len max. , split(), . , , , .

.

!

+3
3

, myfile - . izip_longest itertools , "0" :

[('1', '1', '1', '1', '2'),  ('2', '2', '2', '2', '4'),      
 ('0', '3', '0', '3', '0'), ('0', '0', '0', '4', '0')]

, . :

from itertools import izip_longest

rows = [line.split() for line in myfile]            # Read
rows = zip(*izip_longest(*rows, fillvalue="0"))     # Add zeroes
print "\n".join(" ".join(row) for row in rows)      # Write

: (imho elegant) (8.55 usec 7.08 usec), :

rows = [line.split() for line in myfile]
maxlen = max(len(x) for x in rows)
for row in rows:
    print " ".join(row + ["0"] * (maxlen - len(row)))

Re:

, , , . .

from itertools import izip_longest

rows = [line.split() for line in myfile]
columns = list(izip_longest(*rows, fillvalue="0"))
column_width = [max(len(num) for num in col) for col in columns]

# We make a template of the form "{0:>a} {1:>b} {2:>c} ...",
# where a, b, c, ... are the column widths:
column_template = "{{{0}:>{1}s}}"
row_template = " ".join(column_template.format(i, n) for
    i, n in enumerate(column_width))

print "\n".join(row_template.format(*row) for row in zip(*columns))
+2

, . , .

, str.split() , . .

str.split()

+1

Something like this, but I also believe that it should be updated, as not everything is clear in your question:

tst="""
       1 2
       1 2 3
       1 2
       1 2 3 4
       2 4
    """
res = [line for line in tst.split('\n') if line != '']
mLen = max(len(line) for line in res)   
print '\n'.join(list((line + ' 0' * ((mLen - len(line))//2) for line in res)))
0
source

All Articles