Dynamic table formatting allows you to adapt table presentations based on data characteristics, content types, and specific requirements. This approach provides flexibility and enhances data readability.
from termcolor import colored
def format_table_with_conditions(data):
for row in data:
if row[1] > 30: ## Age condition
formatted_row = [
colored(row[0], 'green'),
colored(str(row[1]), 'red'),
colored(row[2], 'blue')
]
print(" | ".join(formatted_row))
else:
print(" | ".join(map(str, row)))
data = [
["Alice", 28, "New York"],
["Bob", 35, "San Francisco"],
["Charlie", 42, "Chicago"]
]
format_table_with_conditions(data)
Dynamic Column Width
def dynamic_column_width(data):
## Calculate maximum width for each column
col_widths = [max(len(str(row[i])) for row in data) for i in range(len(data[0]))]
## Print formatted table
for row in data:
formatted_row = [
str(val).ljust(width) for val, width in zip(row, col_widths)
]
print(" | ".join(formatted_row))
data = [
["Name", "Age", "City"],
["Alice", 28, "New York"],
["Bob", 35, "San Francisco"],
["Charlie", 42, "Chicago"]
]
dynamic_column_width(data)
graph TD
A[Input Data] --> B[Analyze Data Characteristics]
B --> C{Formatting Conditions}
C -->|Age Condition| D[Color Formatting]
C -->|Column Width| E[Dynamic Width]
D --> F[Generate Formatted Table]
E --> F
Technique |
Pros |
Cons |
Static Formatting |
Simple Implementation |
Limited Flexibility |
Conditional Formatting |
Adaptive Presentation |
Increased Complexity |
Dynamic Width |
Improved Readability |
Performance Overhead |
- Implement flexible formatting logic
- Consider data type and content
- Balance readability with performance
- Use libraries for advanced formatting
import timeit
def measure_formatting_performance():
## Performance measurement code
setup_code = """
data = [["Alice", 28, "New York"], ["Bob", 35, "San Francisco"]]
def dynamic_format(data):
col_widths = [max(len(str(row[i])) for row in data) for i in range(len(data[0]))]
return col_widths
"""
performance = timeit.timeit(
"dynamic_format(data)",
setup=setup_code,
number=10000
)
print(f"Formatting Performance: {performance} seconds")
measure_formatting_performance()
LabEx recommends exploring these dynamic formatting techniques to create more intelligent and adaptive table presentations in Python.