[英]How to convert list of lists to a string with a new line
我有這個代碼:
def table(h, w):
table = [['.' for i in range(w)] for j in range(h)]
return table
返回這個
[
['.', '.', '.', '.'], ['.', '.', '.', '.'], ['.', '.', '.', '.'], ['.', '.', '.', '.']
]
如何讓它返回這個?
....
....
....
....
你不能直接返回這樣的東西。 這與任何數據類型無關。 但是,您可以創建一個 function 來格式化 output ,就像給定您當前的表表示形式一樣:
def print_table(table):
for row in table:
print(''.join(row))
這為您提供了您想要的 output:
....
....
....
....
編輯:現在我考慮一下,這是可能的。 但是你只會返回你的表的字符串表示,而不是它的結構(我假設你需要):
def table(h, w):
table = ''
for row in range(h):
table += '.' * w + '\n'
return table
你可以試試這個
def table(h, w):
table = '\n'.join(['.'*w]) for j in range(h)])
return table
問題已經問到我如何在列表 Comperhansion 中的列表末尾出現 append \n
答案:
(唯一)方法實際上是將結果(列表類型)格式化為字符串:
def table(h, w): table = [['.' for i in range(w)] for j in range(h)] return table def format_table(table_): return "[\n" + ''.join(["\t" + str(line) + ",\n" for line in table_]) + "]" print(format_table(table(3,3)))
Output:
[ ['.', '.', '.'], ['.', '.', '.'], ['.', '.', '.'], ]
對於這個:
def format_table(table_):
return ''.join([''.join([e for e in line]) + ",\n" for line in table_])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.