通过组合列表构建“表”

时间:2015-09-02 18:51:05

标签: python list

我正在尝试通过组合来自两个列表的数据在python中构造一些可呈现的表。

作为一个例子,假设我在比赛中记录了参赛者,并且每个人都有名字,时间和其他任意测量值:

headings = ['Name:','Time:','Awesomeness:']

info = [('Foo', 15.24242, 100), ('Bar', 421.333, 10), ('Pyth the Python', 3.333, 9000)]

我通过使函数neatomatic9000使表格的列缩进正确而应用了一些格式。

def neatomatic9000(something):
    print("{0: <20}".format(something), end = '')

for i in headings:
    neatomatic9000(i)
print('\n')
for j in info:
    for k in j:
        neatomatic9000(k)
    print('\n')

我的表格印刷如下:

Name:               Time:               Awesomeness:        

Foo                 15.24242            100                 

Bar                 421.333             10                  

Pyth the Python     3.333               9000 

哪个看起来没问题,但是我试图将标题作为左侧列的表格 - 基本上我试图将其转置为如下所示:

Name:               Foo               Bar            Pyth the Python

Time:               15.24242          421.333        3.333        

Awesomeness:        100               10             9000

编辑:另一方面,python真的似乎没有检查是否某个东西是一个数字,无论它是浮点数还是整数。我似乎无法合并条件来检查条目是否为数字,然后使用 "{:.2f}".format(k)

将其四舍五入到小数点后两位

4 个答案:

答案 0 :(得分:1)

你的意思是这样吗?

for num, heading in enumerate(headings):
    neatomatic9000(heading)
    for j in info:
        neatomatic9000(j[num])
    print('\n')

输出:

Name:               Foo                 Bar                 Pyth the Python     

Time:               15.24242            421.333             3.333               

Awesomeness:        100                 10                  9000                

enumerate功能会将[a, b, c]之类的列表转换为[(0, a), (1, b), (2, c)]之类的内容。我们想要每个标题一行,这就是我们的外循环。然后对于第0个标题,我们打印每个参赛者的第0个值。对于下一个标题,我们打印每个参赛者的下一个值,依此类推。

请注意,这基本上就是你的循环,但内心深处。

答案 1 :(得分:1)

关于确定python对象是否为数字(int,float等),请参阅here。简而言之,“来自数字导入号码”......“isinstance(obj,Number)”

答案 2 :(得分:0)

不看你的代码:

for left_heading in headings: # for every heading
    row = left_heading # start with the heading
    for info in infos: # from data
        row+= str(info[n])+'\t' # add data to heading
    n+=1 # move to next index
    row+='\n' # add spacing
    print row

答案 3 :(得分:0)

headings = ['Name:','Time:','Awesomeness:']
info = [('Foo', 15.24242, 100), ('Bar', 421.333, 10), ('Pyth the Python', 3.333, 9000)]
info = [[info[v][i] for v in range(len(info))] for i, x in enumerate(info)]

def neatomatic9000(something):
    print("{0: <20}".format(something), end = '')

for i, j in enumerate(info):
    neatomatic9000(headings[i])
    for k in j:
        neatomatic9000(k)
    print('\n')
相关问题