Print A List Of Tuples As Table
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 betwee
Solution 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
Solution 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
Solution 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]) + 1format=('%%-%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
Solution 4:
Python 3 solution:
L = [('element1', 'element2', 'element3'),
('elementelel4', 'element5', 'elementelement6'),
('el7', 'el8', 'elel9')]
max_length_column = []
element_in_tuple = 3for i in range(elements_in_tuple):
max_length_column.append(max(len(e[i])+2for 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
Solution 5:
Python3 very simple solution with tabs i.e. \t
and f-string feature:
a = [(0.3, 0, 1.57),(0.3, 0, -1.57),(0.3, 0, 0.78)]
for q,w,e in a:
print(f"{q}\t{w}\t{e}")
Output:
0.3 0 1.57
0.3 0 -1.57
0.3 0 0.78
Post a Comment for "Print A List Of Tuples As Table"