Reputation: 1
I'm modifying some code that generates 2D barcodes to provide "zoom" functionality. Each barcode is represented by a matrix (list of lists) in Python. Zoom is provided by repeating each matrix element and row by a number of times equal to an integer scaling factor and adding padding where necessary.
This works using nested list comprehensions but I'm curious if there's an elegant way to do it using itertools. Specifically the part where I multiply the number of elements and rows by a scaling factor: [row for row in matrix for _ in range(scaling_factor)]
With list comp I can expand both the height and width to get the new, zoomed matrix.
def expand_height(matrix, height, padding_char=0):
padding = height - scaling_factor * len(matrix)
padding_bottom = padding // 2
padding_top = padding - padding_bottom
result = (
[[padding_char] * width for _ in range(padding_top)]
+ [row for row in matrix for _ in range(scaling_factor)]
+ [[padding_char] * width for _ in range(padding_bottom)]
)
return result
Expanding the width is very similar.
I'm not sure how to use itertools in a similar way. I've tried the code below, but it only replicates the rows by the scaling factor and not the elements in each row.
matrix = list(
itertools.chain.from_iterable(
itertools.repeat(x, scaling_factor)
for x in matrix
)
)
Upvotes: 0
Views: 175