Printing Lists as Tabular Data
Here is an example of how to print a list of lists (a 2D list) as tabular data using Python:
data = [['Name', 'Age', 'Gender'],
['Alice', '25', 'Female'],
['Bob', '30', 'Male'],
['Charlie', '35', 'Male']]
for row in data:
print("\t".join(row))
This code creates a 2D list called "data" that represents a table with 3 columns: "Name", "Age", and "Gender". The for loop iterates through each row of the table, and the print("\t".join(row))
line prints each element of the row separated by a tab character, which makes the data appear as columns in the table.
You can also use the pandas
library to create and format tables, you can use pandas.DataFrame()
to create a DataFrame object from a list of lists and then use .to_string()
method to print the data.
import pandas as pd
data = [['Name', 'Age', 'Gender'],
['Alice', '25', 'Female'],
['Bob', '30', 'Male'],
['Charlie', '35', 'Male']]
df = pd.DataFrame(data)
print(df.to_string())