有没有办法使用itertools调整矩阵(列表列表)?
我正在修改一些生成2D条形码以提供“缩放”功能的代码。 每个条形码由Python中的矩阵(列表列表)表示。 通过重复每个矩阵元素和行相等于整数缩放系数并在必要时添加填充物来提供变焦。
这是使用嵌套列表综合的作品,但是我很好奇是否有一种优雅的方法可以使用Itertools进行操作。特别是我将元素和行数乘以缩放因子的部分:[rangix for _ in range(scaling_factor)的行(scaping_factor)的行(scaping_factor)]
comp i可以将高度和宽度扩展到获取新的缩放矩阵。
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
扩展宽度非常相似。
我不确定如何以类似的方式使用Itertools。我已经尝试了下面的代码,但是它仅通过缩放因子复制行而不是每行元素。
matrix = list(
itertools.chain.from_iterable(
itertools.repeat(x, scaling_factor)
for x in matrix
)
)
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
)
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论