在特定位置填充零。
我有一个小问题。我有一个文件,格式如下:
1 2
1 2 3
1 2
1 2 3 4
2 4
代码中的值实际上代表的是数字(不一定是单个数字),可以是任何数字,也可以是浮点数。
输入文件:在某一行中,每个数字之间用一个空格分开(分隔符不能是其他字符,只能是空格)。
我的任务:我想把空白的地方填充为零,让它看起来像这样,也就是说,填充空白的地方,使其呈现出一个整齐的矩阵格式:
1 2 0 0
1 2 3 0
1 2 0 0
1 2 3 4
2 4 0 0
输出文件:同样的规则适用。在某一行中,每个数字之间也只能用一个空格分开。
使用的语言:Python(或者如果可能的话,也可以用Shell)
我知道有一个叫做zfill的函数,但我觉得这对我帮助不大。
我的解决方案:找出每行的最大长度的一半,使用len和max函数。然后,使用split()方法,在每行的合适位置填充零。我担心这可能会变成一段乱七八糟的代码,我相信还有更好的方法来完成这个任务。
欢迎任何建议。
谢谢!
3 个回答
大概是这样的 - 不过我觉得这个内容应该更新一下,因为你提问的内容并不是很清楚:
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)))
你可以逐行读取文件,数一数里面有多少个数字。然后把这一行写入一个新的临时文件中,接着把其他内容添加到这个临时文件里。如果需要的话,你可以用这个临时文件来覆盖原来的文件。
要数数字的数量,你可以用 str.split()
方法,选择空格作为分隔符,这样就能得到一个列表,列表里的项数就是数字的数量。把你的数字添加进去也很简单。
假设 myfile
是一个已经打开的文件。我们使用来自 itertools 的 izip_longest 来遍历输入文件的列,对于缺失的值用 "0"
来填充:
[('1', '1', '1', '1', '2'), ('2', '2', '2', '2', '4'),
('0', '3', '0', '3', '0'), ('0', '0', '0', '4', '0')]
然后我们只需再次使用 zip 将这个输出组合起来,这样就能恢复填充了零的行。下面是代码:
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
编辑: 上面的(我认为很优雅的)解决方案比简单的方法稍微慢一点(8.55 微秒对比 7.08 微秒):
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)))
回复:评论
如果你想对齐列,最简单的方法是修改第一种方法,因为在那种情况下,我们已经有了按列排列的数字。这使得找到列宽变得简单。
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))