Print a list of tuples as table

梦想的初衷 提交于 2021-02-10 14:53:17

问题


I have a list o tuples:

list = [(element1, element2, element3), (elementelel4, element5, elementelement6), (el7, el8, elel9)]

I want to print it as a table (so the distance between elements should be the same):

HEADER1       HEADER2    HEADER3
element1      element2   element3
elementelel4  element5   elementelement6
el7           el8        elel9

I was trying to use some examples which I found, but it was used to print a list of lists, and I have a list of tuples.


回答1:


Using Format Specification Mini-Language

print "HEADER1       HEADER2    HEADER3"
for ele1,ele2,ele3 in l:
    print "{:<14}{:<11}{}".format(ele1,ele2,ele3)

HEADER1       HEADER2    HEADER3
element1      element2   element3
elementelel4  element5   elementelement6
el7           el8        elel9



回答2:


You can use ljust for left-aligning the element within a fixed width

column_width=20
for row in list:             
    for el in row:         
        print el.ljust(column_width), 
    print

output

element1             element2             element3            
elementelel4         element5             elementelement6     
el7                  el8                  elel9  



回答3:


Assume that, all tuples in the list is of the same length, you can use this:

l = [('element1', 'element2', 'element3'), ('elementelel4', 'element5', 'elementelement6'), ('el7', 'el8', 'elel9')]
width = max(len(e) for t in l for e in t[:-1]) + 1 
format=('%%-%ds' % width) * len(l[0])
print '\n'.join(format % tuple(t) for t in l)

Output:

element1     element2     element3
elementelel4 element5     elementelement6
el7          el8          elel9



回答4:


Python 3 solution:

L = [('element1', 'element2', 'element3'),  
     ('elementelel4', 'element5', 'elementelement6'),  
     ('el7', 'el8', 'elel9')]

max_length_column = []
element_in_tuple = 3

for i in range(elements_in_tuple):
    max_length_column.append(max(len(e[i])+2 for e in L))    

for e in L:
    for i in range(element_in_tuple):
        print(e[i].ljust(max_length_column[i]), end='')
    print()

output:

element1      element2  element3         

elementelel4  element5  elementelement6  

el7           el8       elel9  


来源:https://stackoverflow.com/questions/25403249/print-a-list-of-tuples-as-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!