簡體   English   中英

我需要按行和列打印二維列表 mult_table

[英]I need to print the two-dimensional list mult_table by row and column

到目前為止我有這個但我被告知我不會有一個'| ' 最后,就在兩者之間。

user_input= input()
lines = user_input.split(',')

# This line uses a construct called a list comprehension, introduced elsewhere,
# to convert the input string into a two-dimensional list.
# Ex: 1 2, 2 4 is converted to [ [1, 2], [2, 4] ]

mult_table = [[int(num) for num in line.split()] for line in lines]

for row in mult_table:
    for cell in row:
        print(cell, end=' | ')
    print()

這些是我得到的錯誤。

Testing with input: '1 2 3,2 4 6,3 6 9'
Output differs. See highlights below. 
Special character legend
Your output
1 | 2 | 3 | 
2 | 4 | 6 | 
3 | 6 | 9 | 
Expected output
1 | 2 | 3
2 | 4 | 6
3 | 6 | 9
Testing with input: '1 2 3 4,2 4 6 8,3 6 9 12,4 8 12 16'
Output differs. See highlights below. 
Special character legend
Your output
1 | 2 | 3 | 4 | 
2 | 4 | 6 | 8 | 
3 | 6 | 9 | 12 | 
4 | 8 | 12 | 16 | 
Expected output
1 | 2 | 3 | 4
2 | 4 | 6 | 8
3 | 6 | 9 | 12
4 | 8 | 12 | 16

誰能幫忙?

在您當前的方法中,您必須檢查該元素是否是數字循環中的最后一個元素並相應地更改結尾:

for row in mult_table:
    for i in range(len(row)):
        cell = row[i]
        print(cell, end=' | ' if i!=len(row)-1 else '')
    print()

另一種方法是使用 sep.join(list) 方法,其中在所有元素之間添加字符串sep並放入一個字符串中:

for row in mult_table:
    print(' | '.join([str(cell) for cell in row]))

編輯:將單元格轉換為字符串。

這種類型的 output 是預期的,因為您正在使用:

打印(單元格,結束='|')

這個結果是添加 ' | ' 在打印每個單元格之后。

相反,您可以打印整行添加 ' | ' 在行元素之間使用 join()。 但這要求行的元素是字符串。 因此,可以使用如下代碼:

row = [str(cell) for cell in row]
for row in mult_table:
    print(" | ".join(row))

您正在使用|打印每個單元格最后在:

print(cell, end=' | ')

您可以檢查這是否是最后一個單元格,如果還有更多單元格,則只打印 pipe 符號,或者將它們全部打印在一個 go 中,並與' | '連接在一起 ' | ' ,像這樣:

for row in mult_table:
    print(' | '.join(row))
    print()

暫無
暫無

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

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