[英]joining outputs corresponding to their original list
Hi I have a nested for loop which processes each element in the list and gives it right alignment and whitespace at the same time. 嗨,我有一个嵌套的for循环,该循环处理列表中的每个元素,并同时为其赋予正确的对齐方式和空白。
I have successfully managed to output the individual elements, but I am currently having trouble joining the outputs into their original lists. 我已经成功地输出了各个元素,但是目前在将输出加入其原始列表时遇到了麻烦。
Below is my code. 下面是我的代码。
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
I have little clue how to reassemble the outputs into their original groupings. 我几乎不知道如何将输出重组为原始分组。 What methods can I use?
我可以使用什么方法?
you are pretty close! 你很亲密! You shouldn't use "input" as the name of your list because it is a python function.
您不应该使用“输入”作为列表名称,因为它是python函数。 I changed it to input2.
我将其更改为input2。 Try this:
尝试这个:
input2 = [[1, 1, 1], [1, 2, 3], [1, 3, 6]]
for row in input2:
print(" ".join([str(x) for x in row]))
The "join" method joins items in a list by the characters provided in the quotes. “ join”方法通过引号中提供的字符将列表中的项目连接起来。 You can call join on the list comprehension for list of lists to display each list in the list of lists how you'd like to view it:
您可以在列表推导中调用join以获得列表列表,以显示列表列表中每个列表的显示方式:
out: 出:
>>> for row in input2:
print(" ".join([str(x) for x in row]))
1 1 1
1 2 3
1 3 6
if I changed the join to a comma: 如果我将联接更改为逗号:
>>> for row in input2:
... print(",".join([str(x) for x in row]))
1,1,1
1,2,3
1,3,6
If you'd like to retain the whitespace in front of each element and store them into a list of their own (I think I understand): 如果您想保留每个元素前面的空白并将它们存储到它们自己的列表中(我想我理解):
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
Now you understand "join" a little better! 现在您对“加入”有了更好的了解!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.