如何在列表综合列表的末尾附加\ n [英] How can I append \n at the end of the list in list comperhansion

查看:221
本文介绍了如何在列表综合列表的末尾附加\ n的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

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

返回此

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

如何使其返回此值?

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

推荐答案

(唯一的)方法实际上是将结果(列表类型)格式化为字符串:

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)))

输出:

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

这篇关于如何在列表综合列表的末尾附加\ n的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆