加入与原始列表相对应的输出

时间:2018-11-15 03:42:03

标签: python python-3.x python-2.7

嗨,我有一个嵌套的for循环,该循环处理列表中的每个元素,并同时为其赋予正确的对齐方式和空白。

我已经成功地输出了各个元素,但是目前在将输出加入其原始列表时遇到了困难。

下面是我的代码。

input = [[1, 1, 1], [1, 2, 3], [1, 3, 6]]
space = len(str(input[-1][-1]))

for row in input:
    for e in row:
        new_element = '{:>{}d}'.format(e, space + 1)
        print(new_element)

>>> [[1, 1, 1], [1, 2, 3], [1, 3, 6]]
 # current output
 1
 1
 1
 1
 2
 3
 1
 3
 6 

 # desired output
 1 1 1
 1 2 3
 1 3 6   

我几乎不知道如何将输出重组为原始分组。我可以使用什么方法?

1 个答案:

答案 0 :(得分:0)

您非常接近!您不应该使用“输入”作为列表名称,因为它是python函数。我将其更改为input2。试试这个:

input2 = [[1, 1, 1], [1, 2, 3], [1, 3, 6]]

for row in input2:
    print(" ".join([str(x) for x in row]))

“ join”方法通过引号中提供的字符将列表中的项目连接起来。您可以在列表理解中调用join以获得列表列表,以显示列表列表中每个列表的显示方式:

退出:

>>> for row in input2:
        print(" ".join([str(x) for x in row]))
1 1 1
1 2 3
1 3 6

如果我将联接更改为逗号:

>>> for row in input2:
...     print(",".join([str(x) for x in row]))
1,1,1
1,2,3
1,3,6 

如果您想保留每个元素前面的空白并将它们存储在它们自己的列表中(我想我理解):

z = []
for row in input2:
    z.append(" ".join([str(x) for x in row]))
print(z)

###['1 1 1', '1 2 3', '1 3 6']

for y in z:
    print(y)

1 1 1
1 2 3
1 3 6

现在,您对“加入”有了更好的了解!