是否有一种简单的内置方法可以将 2D Python 列表打印为 2D 矩阵?
所以这:
[["A", "B"], ["C", "D"]]
会变成类似的东西
A B
C D
我找到了该pprint
模块,但它似乎没有做我想要的。
为了让事情变得有趣,让我们尝试一个更大的矩阵:
matrix = [
["Ah!", "We do have some Camembert", "sir"],
["It's a bit", "runny", "sir"],
["Well,", "as a matter of fact it's", "very runny, sir"],
["I think it's runnier", "than you", "like it, sir"]
]
s = [[str(e) for e in row] for row in matrix]
lens = [max(map(len, col)) for col in zip(*s)]
fmt = '\t'.join('{{:{}}}'.format(x) for x in lens)
table = [fmt.format(*row) for row in s]
print '\n'.join(table)
输出:
Ah! We do have some Camembert sir
It's a bit runny sir
Well, as a matter of fact it's very runny, sir
I think it's runnier than you like it, sir
UPD:对于多行单元格,这样的东西应该可以工作:
text = [
["Ah!", "We do have\nsome Camembert", "sir"],
["It's a bit", "runny", "sir"],
["Well,", "as a matter\nof fact it's", "very runny,\nsir"],
["I think it's\nrunnier", "than you", "like it,\nsir"]
]
from itertools import chain, izip_longest
matrix = chain.from_iterable(
izip_longest(
*(x.splitlines() for x in y),
fillvalue='')
for y in text)
然后应用上面的代码。
如果您可以使用 Pandas(Python 数据分析库),您可以通过将其转换为 DataFrame 对象来漂亮地打印 2D 矩阵:
from pandas import *
x = [["A", "B"], ["C", "D"]]
print DataFrame(x)
0 1
0 A B
1 C D
对于没有任何第三方库的 Python 3:
matrix = [["A", "B"], ["C", "D"]]
print('\n'.join(['\t'.join([str(cell) for cell in row]) for row in matrix]))
输出
A B
C D
你总是可以使用numpy:
import numpy as np
A = [['A', 'B'], ['C', 'D']]
print(np.matrix(A))
输出:
[['A' 'B']
['C' 'D']]
只是为了提供一个更简单的替代方案print('\n'.join(\['\t'.join(\[str(cell) for cell in row\]) for row in matrix\]))
:
matrix = [["A", "B"], ["C", "D"]]
for row in matrix:
print(*row)
解释
*row
unpacks row
,因此print("A", "B")
称为 when row
is ["A", "B"]
,例如。
注意
只有当每列具有相同的宽度时,两个答案才会被很好地格式化。要更改分隔符,请使用sep
关键字。例如,
for row in matrix:
print(*row, sep=', ')
将打印
A, B
C, D
反而。
没有 for 循环的单线
print(*(' '.join(row) for row in matrix), sep='\n')
' '.join(row) for row in matrix)
为每一行返回一个字符串,例如A B
when row
is ["A", "B"]
。
*(' '.join(row) for row in matrix), sep='\n')
解包返回序列的生成器'A B', 'C D'
,因此在给出print('A B', 'C D', sep='\n')
的示例中调用它matrix
。
pandas
比使用prettytable
模块更轻量级的方法
from prettytable import PrettyTable
x = [["A", "B"], ["C", "D"]]
p = PrettyTable()
for row in x:
p.add_row(row)
print p.get_string(header=False, border=False)
产量:
A B
C D
prettytable
有很多选项可以以不同的方式格式化您的输出。
有关更多信息,请参阅https://code.google.com/p/prettytable/
我还推荐tabulate,它也可以选择打印标题:
from tabulate import tabulate
lst = [['London', 20],['Paris', 30]]
print(tabulate(lst, headers=['City', 'Temperature']))
:
City Temperature
------ -------------
London 20
Paris 30
You can update print
's end=' '
so that it prints space instead of '\n' in the inner loop and outer loop can have print()
.
a=[["a","b"],["c","d"]]
for i in a:
for j in i:
print(j, end=' ')
print()
I found this solution from here.
请参阅以下代码。
# Define an empty list (intended to be used as a matrix)
matrix = []
matrix.append([1, 2, 3, 4])
matrix.append([4, 6, 7, 8])
print matrix
# Now just print out the two rows separately
print matrix[0]
print matrix[1]