编程语言
首页 > 编程语言> > python-将输出格式化为表格

python-将输出格式化为表格

作者:互联网

输入示例:

[('b', 'c', 4),
('l', 'r', 5),
('i', 'a', 6),
('c', 't', 7),
('a', '$', 8),
('n', '$', 9)]

[0]包含垂直方向,[1]包含水平方向.

输出示例:

  c r a t $$
b 4  
l   5
i     6
c       7
a         8
n           9

注意:给定足够的元组,整个表可以被填充:P

如何使用[最好]用一行代码在Python中将输出格式化为表格?

解决方法:

这是您修改后的问题的答案:

data = [
    ['A','a','1'],
    ['B','b','2'],
    ['C','c','3'],
    ['D','d','4']
]

# Desired output:
#
#   A B C D
# a 1
# b   2
# c     3
# d       4

# Check data consists of colname, rowname, value triples
assert all([3 == len(row) for row in data])
# Convert all data to strings
data = [ [str(c) for c in r] for r in data]
# Check all data is one character wide
assert all([1 == len(s) for s in r for r in data])

#============================================================================
# Verbose version
#============================================================================
col_names, row_names, values = zip(*data) # Transpose

header_line = '  ' + ' '.join(col_names)
row_lines = []
for idx, (row_name, value) in enumerate(zip(row_names,values)):
    # Use '  '*n to get 2n consecutive spaces.
    row_line = row_name + ' ' + '  '*idx + value
    row_lines.append(row_line)

print header_line
for r in row_lines:
    print (r)

或者,如果这对您来说太长了,请尝试以下操作:

cs, rs, vs = zip(*data)
print ('\n'.join(['  '+' '.join(cs)] + [r+' '+'  '*i+v for i,(r,v) in enumerate(zip(rs,vs))]))

两者都具有以下输出:

  A B C D
a 1
b   2
c     3
d       4

这是您想要的内核(没有阅读器行或标题列)

>>> print('\n'.join([ ''.join([str(i+j+2).rjust(3)
    for i in range(10)]) for j in range(10) ]))

  2  3  4  5  6  7  8  9 10 11
  3  4  5  6  7  8  9 10 11 12
  4  5  6  7  8  9 10 11 12 13
  5  6  7  8  9 10 11 12 13 14
  6  7  8  9 10 11 12 13 14 15
  7  8  9 10 11 12 13 14 15 16
  8  9 10 11 12 13 14 15 16 17
  9 10 11 12 13 14 15 16 17 18
 10 11 12 13 14 15 16 17 18 19
 11 12 13 14 15 16 17 18 19 20

它使用对i和j的嵌套列表推导生成数字i j,然后使用str.rjust()将所有字段填充为三个字符的长度,最后使用一些str.join()s将所有子字符串放在一起.

标签:python,tabular,string-formatting
来源: https://codeday.me/bug/20191010/1886056.html