[英]How to print a 2D list so that each list is on a new line with a space, without any “” or []
I'm having trouble printing a list in a visually appealing manor. 我在以美观的方式打印列表时遇到麻烦。 An example of the list is
列表的一个示例是
[["-", "-", "-", "-"],["-", "-", "-", "-"],["-", "-", "-", "-"]]
(the characters won't all necessarily be the same), but I need to print it without using any functions except print
, range
, len
, insert
, append
, pop
, and I cannot use any dictionaries or maps, or import any libraries or use any list-comprehensions. (字符不一定全部相同),但是我需要打印它而不使用除了
print
, range
, len
, insert
, append
, pop
之外的任何函数,并且我不能使用任何词典或地图,也不能导入任何库或使用任何列表理解。 I in turn want: 我又要:
- - - -
- - - -
- - - -
I tried: 我试过了:
def print_board(board):
for i in board:
row = board[i]
for r in row:
print(*row[r], "\n")
You're close, but you misunderstand how for i in <list>
works. 您接近了,但您误解了
for i in <list>
工作方式。 The iteration variable gets the list elements, not their indexes. 迭代变量获取列表元素,而不是其索引。
Also, row[r]
(if r
were the index) would be just a single string, not a list, so you don't need to unpack it with *row[r]
. 另外,
row[r]
(如果r
是索引)将只是一个字符串,而不是列表,因此您无需使用*row[r]
对其进行解包。
There's no need to include "\\n"
in the print()
call, since it ends the output with a newline by default -- you would have to override that with the end=""
option to prevent it. 无需在
print()
调用中包含"\\n"
,因为默认情况下,它以换行符结束输出-您必须使用end=""
选项覆盖该输出,以防止出现这种情况。
for row in board:
for col in row:
print(col, end=" ") # print each element separated by space
print() # Add newline
board = [["-", "-", "-", "-"],["-", "-", "-", "-"],["-", "-", "-", "-"]]
for row in board:
print(*row)
This is the easiest way, but relies on argument unpacking (that *
star before the row
). 这是最简单的方法,但是依赖于参数解压缩(
row
之前加*
)。 If you can't use that for whatever reason then you can use the keyword arguments to print
to achieve the same result 如果由于某种原因不能使用它,则可以使用关键字参数进行
print
以达到相同的结果
for row in board:
for cell in row:
print(cell, end=' ')
print()
With better named variables this migh lead to better understanding: 使用更好的命名变量可以更好地理解:
def print_board(board):
for innerList in board:
for elem in innerList:
print(elem + " ", end ='') # no \n after print
print("") # now \n
b = [["-"]*4]*4
print_board(b)
print(b)
Output: 输出:
- - - -
- - - -
- - - -
- - - -
[['-', '-', '-', '-'], ['-', '-', '-', '-'], ['-', '-', '-', '-'], ['-', '-', '-', '-']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.