Skip to content

Instantly share code, notes, and snippets.

@thehappycheese
Last active January 17, 2023 09:05
Show Gist options
  • Save thehappycheese/d445d47785bcd7f360572388a8d45f1c to your computer and use it in GitHub Desktop.
Save thehappycheese/d445d47785bcd7f360572388a8d45f1c to your computer and use it in GitHub Desktop.
Print a list in nice columns
# inspired by https://stackoverflow.com/questions/1524126/how-to-print-a-list-more-nicely
# needs refinement before I post as answer though. I'll update this at some point
from typing import Iterable, Literal
def print_columns(data:Iterable, columns:int=3, sep:str=" ", alignment:Literal[">","<","^"]=">"):
"""Prints a list of objects in columns.
`data` should be an iterable object, such as a list. Each element of data will be converted to a string using the built in `str()`
`sep` is a string used to separate the columns. defaults to `' '`
`alignment` is a string used to align the columns. It can take the values `">"`, `"<"`, or `"^"` which mean right align, left align, centre align respectively. defaults to `'>'`.
Example:
>>> print_columns(["aaaa","b","c","d","e","f","g","h","i","j","kkk","l","m","n","o"], 3, " ", "<")
aaaa b c
d e f
g h i
j kkk l
m n o
"""
data = [*data]
if len(data)==0:
print("")
return
data += [""]*(len(data) - len(data)//columns*columns)
column_data = []
column_lengths = []
for i in range(columns):
column_data.append(
new_column := list(map(str, data[i::columns])),
)
column_lengths.append(max(len(item) for item in new_column))
datas, lengths = zip(*zip(column_data,column_lengths))
outstring=[]
for data in zip(*datas):
fmt_string = sep.join(f"{{:{alignment}{length}}}" for length in lengths)
outstring.append(fmt_string.format(*data))
print("\n".join(outstring))
import numpy as np
import pandas as pd
def print_columns(items, num_columns=6, sep=" ", read_down=True):
ss = pd.concat([
pd.Series(list(items)),
pd.Series(
[""] * int(np.ceil(len(items) / num_columns)*num_columns - len(items))
)
],
ignore_index=True
)
if read_down:
ss = pd.DataFrame(ss.values.reshape((num_columns,-1))).transpose()
else:
ss = pd.DataFrame(ss.values.reshape((-1, num_columns)))
widths = ss.apply(lambda item: item.str.len().max(), axis="rows")
for column, width in zip(ss.columns, widths):
ss[column] = ss[column].str.ljust(width,fillchar=" ")
for index, row in ss.iterrows():
print(sep.join(row))
print_columns_2(corpex.columns, num_columns=8, read_down=True)
# aaaa e i m
# b f j n
# c g kkk o
# d h l
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment