-1

示例输入:

[('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

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

4

2 回答 2

4

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

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

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

于 2012-05-18T05:22:42.640 回答
1

假设 python 2.x,它有点难看,但它是功能性的:

import operator
from functools import partial
x = range(1,11)
y = range(0,11)
multtable = [y]+[[i]+map(partial(operator.add,i),y[1:]) for i in x]
for i in multtable:
    for j in i:
        print str(j).rjust(3),
    print

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

您的问题是如此具体,很难做出一个真正的通用示例。

不过,这里重要的部分是制作表格的部分,而不是实际的打印:

[map(partial(operator.add,i),y[1:]) for i in x]
于 2012-05-18T05:20:12.713 回答