반응형
다음 형식 (예)으로 저장된 데이터 (숫자)가 있습니다.
234 127 34 23 45567
23 12 4 4 45
23456 2 1 444 567
...
숫자를 정렬하고 다음과 같이 얻는 파이썬 방식의 방법이 있습니까?
234 127 34 23 45567
23 12 4 4 45
23456 2 1 444 567
(열 크기를 예측할 수 없습니다).
해결 방법
다음은 가변 열 너비의 형식을 지정하는 방법을 보여주는 간단한 자체 포함 예제입니다.
data = '''234 127 34 23 45567
23 12 4 4 45
23456 2 1 444 567'''
# Split input data by row and then on spaces
rows = [ line.strip().split(' ') for line in data.split('\n') ]
# Reorganize data by columns
cols = zip(*rows)
# Compute column widths by taking maximum length of values per column
col_widths = [ max(len(value) for value in col) for col in cols ]
# Create a suitable format string
format = ' '.join(['%%%ds' % width for width in col_widths ])
# Print each row using the computed format
for row in rows:
print format % tuple(row)
다음을 출력합니다.
234 127 34 23 45567 23 12 4 4 45 23456 2 1 444 567
참조 페이지 https://stackoverflow.com/questions/3685195
반응형
'파이썬' 카테고리의 다른 글
파이썬 Django - The current URL, , didn't match any of these (0) | 2020.11.04 |
---|---|
파이썬에서 하나의 if 문에 대해 여러 조건을 갖는 방법 (0) | 2020.11.04 |
파이썬 How to upload a file to Google Cloud Storage on Python 3? (0) | 2020.11.04 |
파이썬 What to download in order to make nltk.tokenize.word_tokenize work? (0) | 2020.11.04 |
파이썬 Compare 2 excel files using Python (0) | 2020.11.04 |
댓글