본문 바로가기
파이썬

파이썬 숫자 열 정렬 (표 형식으로 출력 인쇄)

by º기록 2020. 11. 4.
반응형

다음 형식 (예)으로 저장된 데이터 (숫자)가 있습니다.

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

 

 

반응형

댓글