漂亮的打印2D Python列表

时间:2012-11-04 00:12:56

标签: python matrix

是否有一种简单的内置方式将2D Python列表打印为2D矩阵?

所以这个:

[["A", "B"], ["C", "D"]]

会变成类似

的东西
A    B
C    D

我找到了pprint模块,但它似乎没有做我想要的。

10 个答案:

答案 0 :(得分:58)

为了让事情变得有趣,让我们尝试一个更大的矩阵:

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)

然后应用上面的代码。

另见http://pypi.python.org/pypi/texttable

答案 1 :(得分:25)

如果您可以使用Pandas(Python数据分析库),您可以通过将其转换为DataFrame对象来漂亮地打印2D矩阵:

from pandas import *
x = [["A", "B"], ["C", "D"]]
print DataFrame(x)

   0  1
0  A  B
1  C  D

答案 2 :(得分:17)

你总是可以使用numpy

import numpy as np
print(np.matrix(A))

答案 3 :(得分:9)

对于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

答案 4 :(得分:1)

freedom 6933 6.0 0.1 57040 13040 ? S 16:55 0:01 /usr/local/bin/php53.cgi -c .:/home/freedom/:/etc index.php 更轻量级的方法是使用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 有很多选项可以用不同的方式格式化输出。

有关详细信息,请参阅https://code.google.com/p/prettytable/

答案 5 :(得分:1)

仅提供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打开row的封包,例如,print("A", "B")row时将调用["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 Brow时的["A", "B"]

*(' '.join(row) for row in matrix), sep='\n')解压缩生成器并返回序列'A B', 'C D',以便为给出的示例print('A B', 'C D', sep='\n')调用matrix

答案 6 :(得分:0)

您可以更新print的{​​{1}},以便在内部循环中打印空间而不是'\ n',而在外部循环中可以使用end=' '

print()

我从here https://snakify.org/en/lessons/two_dimensional_lists_arrays/找到了这个解决方案。

答案 7 :(得分:0)

如果您使用的是Notebook / IPython环境,那么sympy可以使用IPython.display打印令人愉悦的矩阵:

import numpy as np
from sympy import Matrix, init_printing
init_printing()

print(np.random.random((3,3)))
display(np.random.random((3,3)))
display(Matrix(np.random.random((3,3))))

enter image description here

答案 8 :(得分:0)

我还建议使用tabulate,它也可以选择打印标题:

def place_image(image: Image, point_xy: tuple[int, int], dest: np.ndarray, alpha: float = 1.) -> np.ndarray:

    # Place the merging dot on (500, 500).
    offset_x, offset_y = 500 - point_xy[0], 500 - point_xy[1]

    # Calculate the location of the image and perform alpha blending.
    destination = dest[offset_y:offset_y + image.height, offset_x:offset_x + image.width]
    destination = np.uint8(destination * (1 - alpha) + np.array(image) * alpha)

    # Copy the 'merged' imaged to the destination location.
    dest[offset_y:offset_y + image.height, offset_x:offset_x + image.width] = destination
    return dest

# Add the background image blue with alpha 1
new_image = place_image(blue, point_blue, dest=new_image, alpha=1)

# Add the second image with 40% opacity
new_image = place_image(green, point_green, dest=new_image, alpha=0.4)

# Store the resulting image.
image = Image.fromarray(new_image)
image.save('result.png')

from tabulate import tabulate

lst = [['London', 20],['Paris', 30]]
print(tabulate(lst, headers=['City', 'Temperature']))

答案 9 :(得分:-1)

请参阅以下代码。

# 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]