예쁜 프린트 2D Python 목록
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)
그런 다음 위의 코드를 적용하십시오.
http://pypi.python.org/pypi/texttable 참조
Pandas (Python 데이터 분석 라이브러리)를 사용할 수 있다면 2D 행렬을 DataFrame 객체로 변환하여 예쁘게 인쇄 할 수 있습니다.
from pandas import *
x = [["A", "B"], ["C", "D"]]
print DataFrame(x)
0 1
0 A B
1 C D
항상 numpy 사용할 수 있습니다 .
import numpy as np
A = [['A', 'B'], ['C', 'D']]
print(np.matrix(A))
산출:
[['A' 'B']
['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
모듈 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
다양한 방식으로 출력 형식을 지정할 수있는 많은 옵션이 있습니다.
See https://code.google.com/p/prettytable/ for more info
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 https://snakify.org/en/lessons/two_dimensional_lists_arrays/.
See the following code.
# 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]
ReferenceURL : https://stackoverflow.com/questions/13214809/pretty-print-2d-python-list
'programing' 카테고리의 다른 글
epoch에서 날짜 형식 변환 (0) | 2021.01.18 |
---|---|
동시성 : C ++ 11 메모리 모델의 원자 및 휘발성 (0) | 2021.01.18 |
Python을 통해 연결할 때 기본 Mysql 연결 시간 제한을 어떻게 변경할 수 있습니까? (0) | 2021.01.18 |
부트 스트랩 : 열 사이에 여백 / 패딩 공간 추가 (0) | 2021.01.18 |
PHP. (0) | 2021.01.18 |