简体   繁体   English

转义列表理解中的“\\n”新行与 Python 中的 for 循环

[英]Escaping "\n" new line in list comprehension vs for loop in Python

Escaping "\\n" new line in list comprehension in Python在 Python 中的列表理解中转义“\\n”新行

for loop for循环

string_grid = ''
for i in self.board:
    string_grid += "\n" + str(i)
return string_grid

Returns:返回:

[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]

But how come the list comprehension :但是如何理解列表

return str(["\n" + str(col) for col in self.board])


returns this:返回这个:

['\n[0, 0, 0, 0, 0]', '\n[0, 0, 0, 0, 0]', '\n[0, 0, 0, 0, 0]', '\n[0, 0, 0, 0, 0]', '\n[0, 0, 0, 0, 0]']

I have been trying to make it work for a long time but no matter what I do, the new-line is not being escaped in the stdout.我一直试图让它工作很长时间,但无论我做什么,新行都没有在标准输出中被转义。

In the first example, you create a string, in the second a list.在第一个示例中,您创建一个字符串,在第二个示例中创建一个列表。

You have to join the list to a string:您必须将列表加入一个字符串:

return ''.join("\n{0}".format(col) for col in self.board)

This might help you:这可能会帮助您:

board = [[0] * 5] * 5       # Produce an empty board
print board                 # Display the board as a list of lists

print("\n".join([str(row) for row in board]))

For each row, convert the list of board numbers into a textual representation.对于每一行,将板号列表转换为文本表示。 Use the join function to join each row in the resulting list with a newline.使用join函数将结果列表中的每一行与换行符连接起来。 Giving the following output:给出以下输出:

[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]

Replace print() with returnreturn替换print()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM