Python 排列数字列(以表格格式打印输出)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3685195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:14:54  来源:igfitidea点击:

Line up columns of numbers (print output in table format)

python

提问by pb100

I have data (numbers) saved in the following format (example):

我有以下格式保存的数据(数字)(示例):

234 127 34 23 45567  
23 12 4 4 45  
23456 2 1 444 567  
...

Is there any python-way method to line up the numbers and get them as

是否有任何 python-way 方法来排列数字并将它们作为

  234  127  34   23  45567  
   23   12   4    4     45  
23456    2   1  444    567 

(I cannot predict the column size).

(我无法预测列大小)。

采纳答案by Kevin Jacobs

Here is a simple, self-contained example that shows how to format variable column widths:

这是一个简单的、自包含的示例,展示了如何设置可变列宽的格式:

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)

which outputs:

输出:

  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

回答by Rahul

回答by gimel

You need some way of finding the column size, maybe by reading all the data and finding the maximum width.

您需要某种方法来查找列大小,可能是通过读取所有数据并找到最大宽度。

>>> line='234 127 34 23 45567'
>>> line.split()
['234', '127', '34', '23', '45567']
>>> max(map(len, line.split()))
5

Repeat over all lines, to find column size (e.g., 5). Constructing a formatted line with percent formattingis straightforward.

在所有行上重复,以找到列大小(例如,5)。构造带格式的行percent formatting很简单。

>>> colsize = 5
>>> ' '.join(('%*s' % (colsize, i) for i in line.split()))
'  234   127    34    23 45567'
>>> 

回答by miku

#!/usr/bin/env python

class ALIGN:
    LEFT, RIGHT = '-', ''

class Column(list):
    def __init__(self, name, data, align=ALIGN.RIGHT):
        list.__init__(self, data)
        self.name = name
        width = max(len(str(x)) for x in data + [name])
        self.format = ' %%%s%ds ' % (align, width)

class Table:
    def __init__(self, *columns):
        self.columns = columns
        self.length = max(len(x) for x in columns)
    def get_row(self, i=None):
        for x in self.columns:
            if i is None:
                yield x.format % x.name
            else:
                yield x.format % x[i]
    def get_rows(self):
        yield ' '.join(self.get_row(None))
        for i in range(0, self.length):
            yield ' '.join(self.get_row(i))

    def __str__(self):
        return '\n'.join(self.get_rows())   

For your example:

对于您的示例:

if __name__ == '__main__':
    print Table(
        Column("", [234, 32, 23456]),
        Column("", [127, 12, 2]),
        Column("", [34, 4, 1]),
        Column("", [23, 4, 444]),
        Column("", [45567, 45, 567])
    )

It will yield:

它将产生:

   234   127   34    23   45567 
    32    12    4     4      45 
 23456     2    1   444     567 

Adapted from http://code.activestate.com/recipes/577202-render-tables-for-text-interface/

改编自http://code.activestate.com/recipes/577202-render-tables-for-text-interface/

回答by John La Rooy

>>> rows = """234 127 34 23 45567
... 23 12 4 4 45
... 23456 2 1 444 567"""

first convert the rows into a 2d array (list of lists)

首先将行转换为二维数组(列表列表)

>>> arr=[x.split() for x in rows.split("\n")]

now compute the space each field will need to fit into

现在计算每个字段需要适合的空间

>>> widths = [max(map(len,(f[i] for f in tab))) for i in range(len(arr[0]))]

and pad each element to fit into that space

并填充每个元素以适应该空间

>>> [[k.rjust(widths[i]) for i,k in enumerate(j)] for j in arr]
[['  234', '127', '34', ' 23', '45567'], ['   23', ' 12', ' 4', '  4', '   45'], ['23456', '  2', ' 1', '444', '  567']]

finally join the array back into a string

最后将数组连接回一个字符串

>>> print "\n".join("  ".join(k.rjust(widths[i]) for i,k in enumerate(j)) for j in arr)
  234  127  34   23  45567
   23   12   4    4     45
23456    2   1  444    567

回答by Kody

Integer in front of the d is what column the integers will start after the previous number so you can line them up however you see fit

d 前面的整数是整数将在前一个数字之后开始的列,因此您可以将它们排成一行,但您认为合适

print("{0:4d} {1:4d} {2:4d} {3:4d} {4:4d}".format(234, 127, 34, 23, 45567))

print("{0:4d} {1:4d} {2:4d} {3:4d} {4:4d}".format(234, 127, 34, 23, 45567))

repeat as necessary

根据需要重复

回答by Gnubie

Kevin Jacobs's answer modified to allow a variable number of integers on each row:

凯文·雅各布斯 (Kevin Jacobs) 的答案已修改为允许每行有可变数量的整数

def align(data, delimiter = '\t', is_left_align = True):
  rows = [row.strip().split(delimiter) for row in data.split('\n')]
  cols = map(lambda *row: [str(field) or '' for field in row], *rows)
  widths = [max(len(field) for field in col) for col in cols]
  format = ['%%%s%ds' % ('-' if is_left_align else '', width) for width in widths]
  return '\n'.join([delimiter.join(format[:len(row)]) % tuple(row) for row in rows])

data = '''\
234 127 34 23 45567
23 12 4 4 45
23456 2 1 444 567'''
print(align(data, ' ', False))