簡體   English   中英

如何並排打印列表中的字符串?

[英]How do I print strings in a list side-by-side?

我有一個字符串列表的輸入,我不確定如何並排打印列表中的每個字符串,並在每個字符串下方添加連字符。

示例輸入:

['13 + 11', '12 - 4', '36 + 18']

所需的 output:

  13     12      36

+ 11    - 4    + 18

我試過的:

我嘗試使用for循環遍歷輸入列表中的字符串,並將它們拆分為一個空格:

for i in problems:
    j = i.split(' ')
    print(j)

Output 從嘗試這個:

['13', '+', '11']
['12', '-', '4']
['36', '+', '18']

我嘗試結合splitjoin方法來更改 output,但我缺少一些關鍵知識。 我不知道如何並排打印字符串。 我覺得這與包含換行符有關,但除此之外我遇到了麻煩。

正如您所發現的,使用split會得到這樣的結果:

>>> l = ['13 + 11', '12 - 4', '36 + 18']
>>> list(map(str.split, l))
[['13', '+', '11'], ['12', '-', '4'], ['36', '+', '18']]

現在您可以使用zip()來獲取索引匹配元素:

>>> list(zip(*map(str.split, l)))
[('13', '12', '36'), ('+', '-', '+'), ('11', '4', '18')]

現在只需循環打印它:

>>> for row in zip(*map(str.split, l)):
...     print(*row, sep='\t')
    
13  12  36
+   -   +
11  4   18

為了更接近您的要求,您只能split一次(使用maxsplit參數)並稍微格式化 output :

l = ['13 + 11', '12 - 4', '36 + 18']
for row in zip(*[s.split(' ', 1) for s in l]):
    print(*[f"{num:>6}" for num in row])

會給:

    13     12     36
  + 11    - 4   + 18

為了得到你想要的 output,我試過這個:

join_spaces = '    '
mylist = ['13 + 11', '12 - 4', '36 + 18']
top = []
bottom = []

for each in mylist:
    number1, number2 = each.split(' ', 1)
    bottom.append(number2)
    top.append(number1)

for t in range(len(top)):
    length = " " * (len(bottom[t]) - len(top[t]))
    top[t] = length + top[t]

print(join_spaces.join(top))
print(join_spaces.join(bottom))

不是最干凈的方法(寫得很快)

解釋:對於列表中的每個值,使用 split(' ', 1) 在第一次出現空格處進行拆分; 這將是第一個數字(13、12、36)。 然后將此添加到頂部列表,並將 append rest(“+ 11”,“- 4”,“+ 18”)添加到底部列表。 然后,對於列表頂部的每個值,從頂部 (13, 12, 36) 中減去底部的長度 (“+ 11”、“- 4”、“+ 18”),然后將該數字乘以一個空格. 然后,將空格添加到頂部列表中每個值的開頭,並將列表打印為字符串(連接)

輸出:

  13     12      36
+ 11    - 4    + 18

假設您的表達式始終采用“a '操作' b”的形式:

problems = ['13 + 11', '12 - 4', '36 + 18']

split_problems = []
for i in problems:
    j = i.split(' ')
    split_problems.append(j)

result = ""

for i in range(len(split_problems)):
    result += split_problems[i][0] + " "

result += '\n'

for i in range(len(split_problems)):
    result += split_problems[i][1] + "" + split_problems[i][2] + " "

print(result)

解決方案說明:

首先像你一樣把整個東西分成幾部分,得到一個像[['13', '+', '11'], ['12', '-', '4'], ['36', '+', '18']]

然后遍歷外部元素並打印每個第一個條目,或者在這種情況下 append 將它們打印到結果字符串。 然后再次循環外部元素並在每次迭代或 append 將它們打印到結果字符串中的每個第 2 和第 3 個元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM