Print a list in table format in python

I am trying to print multiple lists (equal length) as table columns.

I am reading data from a .txt file, and at the end of the code I have 5 lists that I would like to print as separated columns, and spaces.

+4
source share
4 answers

I will show you an analogue from 3 lists:

>>> l1 = ['a', 'b', 'c'] >>> l2 = ['1', '2', '3'] >>> l3 = ['x', 'y', 'z'] >>> for row in zip(l1, l2, l3): ... print ' '.join(row) a 1 x b 2 y c 3 z 
+5
source

The statement that you have lists of lists:

 for L in list_of_lists: print " ".join(L) 

The str.join(iterable) function combines the components of iteration over a given string.

Therefore, " ".join([1, 2, 3]) becomes "1 2 3".

In case I might have misunderstood the question and each list should be a column:

 for T in zip(list1, list2, list3, list4, list5): print " ".join(T) 

zip() combines the specified lists into a single list of tuples:

 >>> zip([1,2,3], [4,5,6], [7,8,9]) [(1, 4, 7), (2, 5, 8), (3, 6, 9)] 

Hooray!

+1
source

You can use my beautifultable package. It supports adding data by row or column, or even mixing both approaches. You can insert, delete, update any row or column.

Using

 >>> from beautifultable import BeautifulTable >>> table = BeautifulTable() >>> table.column_headers = ["name", "rank", "gender"] >>> table.append_row(["Jacob", 1, "boy"]) >>> table.append_row(["Isabella", 1, "girl"]) >>> table.append_row(["Ethan", 2, "boy"]) >>> table.append_row(["Sophia", 2, "girl"]) >>> table.append_row(["Michael", 3, "boy"]) >>> print(table) +----------+------+--------+ | name | rank | gender | +----------+------+--------+ | Jacob | 1 | boy | +----------+------+--------+ | Isabella | 1 | girl | +----------+------+--------+ | Ethan | 2 | boy | +----------+------+--------+ | Sophia | 2 | girl | +----------+------+--------+ | Michael | 3 | boy | +----------+------+--------+ 

Good luck

+1
source
 for nested_list in big_container_list print '\t'.join(nested_list) 

c \t is a tab character

quick example:

 In [1]: a = [['1','2'],['3','4']] In [5]: for nested_list in a: ...: print '\t'.join(nested_list) ...: 1 2 3 4 
0
source

Source: https://habr.com/ru/post/1487910/


All Articles