我是一名初學者程式員,正在完成 freecodecamp 上的最終專案之一。
我正在使用 Mac OS python3.10
該問題要求我們創建一個函式,該函式將水平排列的算術問題串列作為引數并垂直重新排列它們。
這是函式呼叫:
arithmetic_arranger(["32 698", "3801 - 2", "45 43", "123 49"])
這是期望的結果:
32 3801 45 123
698 - 2 43 49
----- ------ ---- -----
我能夠垂直重新格式化方程,但我被困在試圖弄清楚如何在同一行上并排列印它們。這是我寫的代碼。
def aa(problem) :
for i in problem[:] :
problem.remove(i)
p = i.split()
# print(p)
ve = '\t{:>5}\n\t{:<1}{:>4}\n\t-----'.format(p[0],p[1],p[2])
print(ve)
return
aa(["32 698", "3801 - 2", "45 43", "123 49"])
這是該代碼的結果。
32
698
-----
3801
- 2
-----
45
43
-----
123
49
-----
我已經嘗試過使用 print(*variable) 和 ''.join。當我嘗試這些解決方案時,我得到了這個。
3 2
6 9 8
- - - - -
3 8 0 1
- 2
- - - - -
4 5
4 3
- - - - -
1 2 3
4 9
- - - - -
感謝您花時間閱讀我的問題,并感謝您的幫助。
uj5u.com熱心網友回復:
當您將字符列印到終端時,游標位置會向前移動。當您列印換行符時,游標會向下移動一個位置。您必須手動再次啟動它才能在上面的行中列印。您可以使用ANSI Escape Codes來控制游標的位置。它更加困難和復雜。
您可以通過更改方程式的表示方式來獲得所需的輸出。將每個方程存盤為[operand1, sign, operand2]。現在,只需在一行中列印所有運算元 1。接下來列印符號和運算元 2。然后列印-----。
def fmt(lst):
op1, sign, op2 = zip(*map(str.split, lst))
line1 = "\t".join([f"{op:>5}" for op in op1])
line2 = "\t".join([f"{s:<1}{op:>4}" for s, op in zip(sign, op2)])
line3 = "-----\t"*len(lst)
print("\n".join([line1, line2, line3])
fmt(["32 698", "3801 - 2", "45 43", "123 49"])
輸出:
32 3801 45 123
698 - 2 43 49
----- ----- ----- -----
uj5u.com熱心網友回復:
這是一個與預期結果完全匹配的解決方案。它決定了每個方程的寬度:
def arithmetic_arranger(equations):
# Parse to list of lists, e.g.:
# [['32', ' ', '698'], ['3801', '-', '2'], ['45', ' ', '43'], ['123', ' ', '49']]
parsed = [equation.split() for equation in equations]
# For each sublist, determine the widest string and build a list of those widths, e.g.:
# [3, 4, 2, 3]
widths = [len(max(items,key=len)) for items in parsed]
# zip() matches each width with each parsed sublist.
# Print the first operands right-justified with appropriate widths.
print(' '.join([f' {a:>{w}}' for w,(a,op,b) in zip(widths,parsed)]))
# Print the operator and the second operand.
print(' '.join([f'{op} {b:>{w}}' for w,(a,op,b) in zip(widths,parsed)]))
# Print the dashed lines under each equation.
print(' '.join(['-'*(w 2) for w in widths]))
arithmetic_arranger(["32 698", "3801 - 2", "45 43", "123 49"])
輸出:
32 3801 45 123
698 - 2 43 49
----- ------ ---- -----
uj5u.com熱心網友回復:
感謝所有花時間提供幫助的人。我使用@MarkTolonen 的提示提出了一個解決方案,他建議我將串列放入串列中。下面是我的解決方案。讓我知道是否有更優雅的方法來做到這一點。
功能:
def aa(problem) :
new_list = list()
for i in problem[:] :
problem.remove(i)
p = i.split()
new_list.append(p)
print(new_list)
for l in new_list :
l1 = '{:>5}'.format(l[:][0])
print(l1,end=' ')
print('')
for l in new_list:
l2 = '{:<1}{:>4}'.format(l[:][1],l[:][2])
print(l2,end=' ')
print('')
for l in new_list:
print('-----',end=' ')
return
函式呼叫:
aa(["32 698", "3801 - 2", "45 43", "123 49"])
結果:
32 3801 45 123
698 - 2 43 49
----- ----- ----- ----- %
還。列印破折號末尾的“%”是什么意思?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/420268.html
標籤:
