有没有办法使用itertools调整矩阵(列表列表)?

发布于 2025-02-03 23:13:31 字数 1040 浏览 1 评论 0原文

我正在修改一些生成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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文