How can I append \n at the end of the list in list comperhansion

限于喜欢 提交于 2019-12-12 07:03:46

问题


I have this code:

def table(h, w):
    table = [['.' for i in range(w)] for j in range(h)]
    return table

which returns this

[
['.', '.', '.'], ['.', '.', '.'], ['.', '.', '.'], ['.', '.', '.']
]

How to make it return this?

[
    ['.', '.', '.'],
    ['.', '.', '.'],
    ['.', '.', '.'],
    ['.', '.', '.']
]

回答1:


The (only) way to do it is actually to format the result (list type) to a string :

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 :

[
    ['.', '.', '.'],
    ['.', '.', '.'],
    ['.', '.', '.'],
]


来源:https://stackoverflow.com/questions/58472978/how-can-i-append-n-at-the-end-of-the-list-in-list-comperhansion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!