首页 > 解决方案 > 如何将列表列表转换为带有新行的字符串

问题描述

我有这个代码:

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

返回这个

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

如何让它返回这个?

....
....
....
....

标签: pythonstringlisttype-conversion

解决方案


不能直接返回这样的东西。这与任何数据类型无关。但是,您可以创建一个函数来格式化输出,就像给定您当前的表表示形式一样:

def print_table(table):
    for row in table:
        print(''.join(row))

这为您提供了所需的输出:

....
....
....
....

编辑:现在我考虑一下,这是可能的。但是你只会返回你的表的字符串表示,而不是它的结构(我假设你需要):

def table(h, w):
    table = ''
    for row in range(h):
        table += '.' * w + '\n'
    return table

推荐阅读