显示python 2d列表,每行后面不带逗号、括号等和换行符
我试图显示一个不带逗号、括号等的Python2D列表,我想在列表的每一行结束后显示一行 这是我的尝试:显示python 2d列表,每行后面不带逗号、括号等和换行符,python,list,Python,List,我试图显示一个不带逗号、括号等的Python2D列表,我想在列表的每一行结束后显示一行 这是我的尝试: ogm = repr(ogm).replace(',',' ') ogm = repr(ogm).replace('[',' ') ogm = repr(ogm).replace("'", ' ') ogm = repr(ogm).replace('"', ' ') print repr(ogm).replace(']',' ') 这是输入: [[0, 0, 0, 0, 0, 0, 0,
ogm = repr(ogm).replace(',',' ')
ogm = repr(ogm).replace('[',' ')
ogm = repr(ogm).replace("'", ' ')
ogm = repr(ogm).replace('"', ' ')
print repr(ogm).replace(']',' ')
这是输入:
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 1, 1, 0, 1, 1, 1, 1], [0, 0, 1, 1, 0, 0, 1, 1, 1, 1], [0, 1, 0, 0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 1, 1, 0, 0], [1, 0, 1, 1, 1, 1, 0, 0, 0, 0]]
这是输出:
"' 0 0 0 0 0 0 0 0 0 0 1 1 0 1 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 1 1 0 1 1 1 1 0 0 1 1 0 0 1 1 1 1 0 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 1 0 0 1 0 1 1 1 1 0 0 0 0 '"
我遇到了两个问题:
for row in list2D:
print " ".join(map(str,row))
也许join适合您:
print "\n".join(" ".join(str(el) for el in row) for row in ogm)
0 0 0 0 0 0 0 0 0 0
1 1 0 1 0 0 0 0 0 0
1 1 1 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0 1 1
0 0 0 0 0 0 1 1 1 0
0 0 0 1 1 0 1 1 1 1
0 0 1 1 0 0 1 1 1 1
0 1 0 0 0 0 0 1 1 0
0 0 0 0 0 0 1 1 0 0
1 0 1 1 1 1 0 0 0 0
如果您想要换位行和列
print "\n".join(" ".join(map(str, line)) for line in zip(*ogm))
顺便说一句,“实际上是两个”没有任何差距
我正在学习python一周。你们给出了一些很好的解决方案。我是这样做的……这也行……) 要使显示更具可读性,可以使用制表符或用空格填充单元格以对齐列
def printMatrix(matrix):
for lst in matrice:
for element in lst:
print(element, end="\t")
print("")
它将显示
6 8 99
999 7 99
3 7 99
而不是
6 8 99
999 7 99
3 7 99
哇,你真是个天才。非常感谢。这可以是
print('\n'.join(map(lambda b:''.join(map(str,b)),list2D))
注意:对类似的事情使用repr
是一种不好的做法。这种方法有效,但可以(显著地)进一步优化。
6 8 99
999 7 99
3 7 99
6 8 99
999 7 99
3 7 99