垂直时如何正确对齐?
我有一个在Python中发挥功能的任务,该功能垂直安排了几个算术问题,因此我所需的输出就是这样:
32 1 9999 523
+ 8 - 3801 + 9999 - 49
---- ------ ------ -----
40 -3800 19998 474
为了产生这样的输出,我写了一个“ for” for tor to the the Cright(参数)此功能的列表是: [“ 32 + 698”,“ 3801-2”,“ 45 + 43”,“ 123 + 49”,“ 555 + 555”]
),将它们分配给变量,然后它应该像所需的输出一样将它们打印出来。要打印出来,我写了这篇文章:
sol = \
( f' {first}'
f'\n{oper}'
f' {second}'
f'\n{dash}'
f'\n {sum}')
lst.append(sol)
{first}
是参数的第一个数字, {oper> {oper}
是操作员, {second}
是第二个数字, {dash}
是可调破折号, {sum}
是算术问题的解决方案。最后一行将垂直算术解决方案附加到列表中,我试图从中水平打印它们。
print(f'{lst[0]} {lst[1]} {lst[2]} {lst[3]}')
但是,我得到的输出是:
32
+ 698
-----
730 3801
- 2
------
3799 45
+ 43
----
88 123
+ 49
-----
172
如何将解决方案均匀地制作并正确对齐?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个简化的版本,没有列表综合,
可能需要解释的唯一部分是创建此列表的第一个循环:
它将每个问题分解为列表[Operand1,operator,operand2]。
这是第一个(可能过于复杂的)版本。
进行一些预处理,并为每行列出一个列表,然后打印每行。
输出:
说明:
lst = list(zip(*[p.split('''for p.s in caresears in respare])))
“ 32 + 698”
变为[“ 32”,“ +”,“ 698”]
[('32','3801','45','123','555'),('+',' - ' - ','+','+','+'), ('698','2','43','49','555')]
[s.rjust(width)for lst [0]]
[“ 32”,“ 3801”,“ 45”,“ 123”,“ 555”]
[f“ {op} {val) 。
[' - ' *(width)] * len(lst [0]),
[str(eval(p))。问题中的p的rjust(width)]
Here's a simplified version with no list comprehensions
The only part that might need explaining is the first for loop that creates this list:
It has broken up each problem into a list [operand1, operator, operand2].
Here's the first (possible overly complex) version.
Do some pre-processing and make a list for each line then print each line.
Output:
Explanation:
lst = list(zip(*[p.split(' ') for p in problems]))
"32 + 698"
becomes["32", "+", "698"]
[('32', '3801', '45', '123', '555'), ('+', '-', '+', '+', '+'), ('698', '2', '43', '49', '555')]
[s.rjust(width) for s in lst[0]]
[" 32", " 3801", " 45", " 123", " 555"]
[f"{op}{val.rjust(width-1)}" for op,val in zip(lst[1], lst[2])]
["+ 698", "- 2", "+ 43", "+ 49", "+ 555"]
['-' * (width)] * len(lst[0]),
[str(eval(p)).rjust(width) for p in problems]