Nov-24-2020, 10:57 PM
How can i format lists in columns so that gap between them are even any they are nicely in line?
Thanks.
Thanks.
Formatting lists
|
Nov-24-2020, 10:57 PM
How can i format lists in columns so that gap between them are even any they are nicely in line?
Thanks.
Nov-24-2020, 11:38 PM
Use a formatting package. As an example, you could look at tabulate, but there are several others.
Otherwise, you need to calculate the size of your fields yourself and enforce that size with formatting commands. Example with tabulate: from tabulate import tabulate table = [["A", "B", "C"], ["D", "Epsilon", "Foxtrot city"], ["South Mangrove", "T", "U"]] print(tabulate(table)) Manual example:table = [["A", "B", "C"], ["D", "Epsilon", "Foxtrot city"], ["South Mangrove", "T", "U"]] for row in table: print("{:15} {:15} {:15}".format(*row))
Nov-25-2020, 08:23 AM
table = [["A", "B", "C"], ["D", "Epsilon", "Foxtrot city"], ["South Mangrove", "T", "U"]] list_len = [len(element) for row in table for element in row] column_width = max(list_len) for row in table: row = "".join(element.ljust(column_width + 2) for element in row) print(row)
Nov-25-2020, 01:12 PM
Use the table master ๐
f-string just try some values to get a fit.lst = [ ["Name", "Email", "ID"], ["Richard", "[email protected]", "55"], ["Tasha", "[email protected]", "99"] ] for inner in lst: print(' | '.join((f"{word:22}" for word in inner))) Could use a max length as shown over to.max_len = max(len(i) for j in lst for i in j) for inner in lst: print(' | '.join((f"{word:{max_len}}" for word in inner)))
Tabulate as shown work fine for this. from tabulate import tabulate lst = [ ["Name", "Email", "ID"], ["Richard", "[email protected]", "55"], ["Tasha", "[email protected]", "99"] ] print(tabulate(lst)) print(tabulate(lst, tablefmt="fancy_grid")) print(tabulate(lst, tablefmt="github"))
Nov-26-2020, 01:18 PM
(Nov-24-2020, 11:38 PM)bowlofred Wrote: Use a formatting package. As an example, you could look at tabulate, but there are several others.
Nov-26-2020, 04:53 PM
It's because you're passing in two different data types,
int and str , and the default for format is to left-justify strings, but right-justify numbers. So they end up on the opposite side.There's no right way to do this. Shrinking the size as small as possible helps. Changing the ints to strs works okay, but you lose the numeric alignment. For small numbers this is okay, but if you have a mix of sizes, it's very confusing. list_a=[[1,2,3,4,5], ['d','h','f','s','g']] #a=0, a=1,a=2, a=3, a=4,a=5 for row in list_a: print("{:15} {:15} {:15} {:15}{:15} ".format(*(str(x) for x in row)))
|
|
Possibly Related Threads… | |||||
Thread | Author | Replies | Views | Last Post | |
Split dict of lists into smaller dicts of lists. | pcs3rd | 3 | 3,273 |
Sep-19-2020, 09:12 AM Last Post: ibreeden |
|
sort lists of lists with multiple criteria: similar values need to be treated equal | stillsen | 2 | 4,980 |
Mar-20-2019, 08:01 PM Last Post: stillsen |