This is similar to How to print a list in Python “nicely”, but I would like to print the list even more nicely -- without the brackets and apostrophes and commas, and even b
Inspired by gimel's answer, above.
import math
def list_columns(obj, cols=4, columnwise=True, gap=4):
"""
Print the given list in evenly-spaced columns.
Parameters
----------
obj : list
The list to be printed.
cols : int
The number of columns in which the list should be printed.
columnwise : bool, default=True
If True, the items in the list will be printed column-wise.
If False the items in the list will be printed row-wise.
gap : int
The number of spaces that should separate the longest column
item/s from the next column. This is the effective spacing
between columns based on the maximum len() of the list items.
"""
sobj = [str(item) for item in obj]
if cols > len(sobj): cols = len(sobj)
max_len = max([len(item) for item in sobj])
if columnwise: cols = int(math.ceil(float(len(sobj)) / float(cols)))
plist = [sobj[i: i+cols] for i in range(0, len(sobj), cols)]
if columnwise:
if not len(plist[-1]) == cols:
plist[-1].extend(['']*(len(sobj) - len(plist[-1])))
plist = zip(*plist)
printer = '\n'.join([
''.join([c.ljust(max_len + gap) for c in p])
for p in plist])
print printer
Results (the second one satisfies your request):
>>> list_columns(foolist)
exiv2-devel fcgi msvcrt qgis-devel
mingw-libs netcdf gdal-grass qgis1.1
tcltk-demos pdcurses-devel iconv php_mapscript
>>> list_columns(foolist, cols=2)
exiv2-devel msvcrt
mingw-libs gdal-grass
tcltk-demos iconv
fcgi qgis-devel
netcdf qgis1.1
pdcurses-devel php_mapscript
>>> list_columns(foolist, columnwise=False)
exiv2-devel mingw-libs tcltk-demos fcgi
netcdf pdcurses-devel msvcrt gdal-grass
iconv qgis-devel qgis1.1 php_mapscript
>>> list_columns(foolist, gap=1)
exiv2-devel fcgi msvcrt qgis-devel
mingw-libs netcdf gdal-grass qgis1.1
tcltk-demos pdcurses-devel iconv php_mapscript