[英]Arrange output vertically and side-by-side in python
所以我想在一个漂亮的栏目中垂直排列算术问题。
代码:`def arithmetic_arranger(问题,计算=假):
for problem in problems:
problem = problem.split()
first_number = problem[0]
second_number = problem[2]
sign = problem[1]
try:
first_number = int(first_number)
second_number = int(second_number)
except:
print('Error: Numbers must only contain digits.')
break
if calculate is True:
if sign == '+':
result = first_number + second_number
else:
result = first_number - second_number
print(f'{first_number}\n{sign} {second_number}\n-----')
if calculate is True:
print(result)
arithmetic_arranger(["32 + 8", "1 - 3801", "9999 + 9999", "523 - 49"], True)`
这是当前的 output:
+ 8
-----
40
1
- 3801
-----
-3800
9999
+ 9999
-----
19998
523
- 49
-----
474
我想把它变成:
32 1 9999 523
+ 8 - 3801 + 9999 - 49
---- ------ ------ -----
40 -3800 19998 474
我试过将第一个数字添加到列表中,然后在行中显示它们,但这并没有真正起作用。
我会通过创建一个 function 来解决这个问题,它将两个数字加/减为数字,而不是字符串。 然后使用len(str(x))
将数字的打印长度推断为字符串,我们可以打印适当数量的前导空格和破折号。
def long_op(x, y, op="+"):
if op == "+":
result = x + y
elif op == "-":
result = x - y
else:
raise ValueError("op must be + or -")
width = max([len(str(i)) for i in [x, y]])
first = " " * (2 + width - len(str(x))) + str(x)
second = op + " " * (1 + width - len(str(y))) + str(y)
bar = "-" * (2 + width)
last = " " * (2 + width - len(str(result))) + str(result)
return "\n".join([first, second, bar, last])
def multi_ops(*args):
long_ops = [long_op(*arg).split("\n") for arg in args]
transpose = list(map(list, zip(*long_ops)))
return "\n".join([" ".join(l) for l in transpose])
print(long_op(32,8))
print()
print(multi_ops([32,8], [1,3801,"-"], [9999,9999], [523,49,"-"]))
Output:
32
+ 8
----
40
32 1 9999 523
+ 8 - 3801 + 9999 - 49
---- ------ ------ -----
40 -3800 19998 474
在tabulate的帮助下,这是一个命题(基于您的代码)。
#pip install tabulate
from tabulate import tabulate
def arithmetic_arranger(problems, calculate=False):
problem_lists = [problem.split() for problem in problems]
if calculate:
results = [eval(" ".join(problem)) for problem in problem_lists]
problem_lists = [problem_lists[i] + [result]
for i, result in enumerate(results)]
problem_lists = list(map(list, zip(*problem_lists)))
problem_lists[1:3] = [[" ".join(x)
for x in zip(problem_lists[1], problem_lists[2])]]
print(tabulate(problem_lists, tablefmt="simple", showindex=False,
numalign="right", stralign="right"))
Output:
arithmetic_arranger(["32 + 8", "1 - 3801", "9999 + 9999", "523 - 49"], True)
--- ------ ------ ----
32 1 9999 523
+ 8 - 3801 + 9999 - 49
40 -3800 19998 474
--- ------ ------ ----
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.