我有一個任務是在 Python 中創建一個函式,它垂直排列幾個算術問題,所以我想要的輸出是這樣的:
32 1 9999 523
8 - 3801 9999 - 49
---- ------ ------ -----
40 -3800 19998 474
為了產生這樣的輸出,我撰寫了一個“for”回圈,它遍歷引數(這個函式的引數是一個串列["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}是運算子,{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
如何使帶有解決方案的字串均勻并正確對齊?
uj5u.com熱心網友回復:
這是一個沒有串列推導的簡化版本
problems = ["32 698", "3801 - 2", "45 43", "123 49", "555 555"]
width = 5
space = " "
lst = []
for problem in problems:
lst.append(problem.split(' '))
for problem in lst:
print(problem[0].rjust(width), end=space)
print()
for problem in lst:
print(f"{problem[1]}{problem[2].rjust(width-1)}", end=space)
print()
for problem in lst:
print("-" * width, end=space)
print()
for problem in problems:
print(str(eval(problem)).rjust(width), end=space)
print()
可能需要解釋的唯一部分是創建此串列的第一個 for 回圈:
[['32', ' ', '698'], ['3801', '-', '2'], ['45', ' ', '43'], ['123', ' ', '49'], ['555', ' ', '555']]
它將每個問題分解為一個串列 [operand1, operator, operand2]。
這是第一個(可能過于復雜)版本。
做一些預處理并為每一行列出一個串列,然后列印每一行。
problems = ["32 698", "3801 - 2", "45 43", "123 49", "555 555"]
width = 5
lst = list(zip(*[p.split(' ') for p in problems]))
lines = [[s.rjust(width) for s in lst[0]],
[f"{op}{val.rjust(width-1)}" for op,val in zip(lst[1], lst[2])],
['-' * (width)] * len(lst[0]),
[str(eval(p)).rjust(width) for p in problems]]
for l in lines: print(' '.join(l))
輸出:
32 3801 45 123 555
698 - 2 43 49 555
----- ----- ----- ----- -----
730 3799 88 172 1110
解釋:
lst = list(zip(*[p.split(' ') for p in problems]))
- 將每個問題拆分為一個串列。例如:
"32 698"變成["32", " ", "698"] - 然后它將每個部分(運算元 1、運算子、運算元 2)壓縮到它們自己的串列中。前任:
[('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])]
- 第 2 行。連接運算子和第二個運算元
- 前任:
[" 698", "- 2", " 43", " 49", " 555"]
['-' * (width)] * len(lst[0]),
- 創建第三行破折號
[str(eval(p)).rjust(width) for p in problems]
- 最后一行以正確的寬度顯示所有總和
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/494621.html
