python - 填充数组的有效方法

标签 python padding

我想知道是否有一种有效的方法可以在 python 中填充数组,而无需使用 numpy.pad()

我知道一种使用嵌套 for 循环的方法,但我想知道是否有更快的方法?

输入:

row padding on top- 2
column padding from left - 1
1 2 3
4 5 6
7 8 9

输出

0 0 0 0
0 0 0 0
0 1 2 3
0 4 5 6
0 7 8 9

我做了什么

y = [[1,2,3],[4,5,6],[7,8,9]]

topPadding = 2
leftPadding = 1
noOfRows = len(y)+topPadding
noOfCols = len(y)+leftPadding

x = [[0 for i in range(noOfCols)] for j in range(noOfRows)]

for i in range(topPadding,noOfRows):
    for j in range(leftPadding,noOfCols):
        x[i][j] = y[i-topPadding][j-leftPadding]
    print()
        
print(x)

输出

[[0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 2, 3], [0, 4, 5, 6], [0, 7, 8, 9]]

最佳答案

使用 list 连接和重复运算符的解决方案:

def concat(x, top, left):
    n = len(x[0])
    return [[0]*(n + left - len(row)) + row for row in [[]]*top + x]

下面是一些非常基本的计时结果,使用您的嵌套 for 循环解决方案与我在 10000x10000 随机数字矩阵上的串联解决方案:

nested: 122.26 s
concat: 5.66 s

测试代码:

import timeit
from random import randint


def concat(x, top, left):
    n = len(x[0])
    return [[0]*(n + left - len(row)) + row for row in [[]]*top + x]


def nested(x, topPadding, leftPadding):
    noOfRows = len(x)+topPadding
    noOfCols = len(x)+leftPadding

    z = [[0 for i in range(noOfCols)] for j in range(noOfRows)]

    for i in range(topPadding,noOfRows):
        for j in range(leftPadding,noOfCols):
            z[i][j] = x[i-topPadding][j-leftPadding]

    return z


test = [[randint(0, 9) for _ in range(10000)] for _ in range(10000)]

t1 = timeit.timeit(
    "nested(test, 4, 2)",
    number=10,
    globals=globals()
)

t2 = timeit.timeit(
    "concat(test, 4, 2)",
    number=10,
    globals=globals()
)

print(nested(test, 4, 2) == concat(test, 4, 2))
print(f"nested: {t1:.2f} s")
print(f"concat: {t2:.2f} s")

完整输出:

True
nested: 122.26 s
concat: 5.66 s

您输入所需高度和宽度的修改版本:

def concat(x, h, w):
    H = h - len(x)
    return [[0]*(w - len(row)) + row for row in [[]]*H + x]

另一个允许向北、南、东和西填充的版本:

def nsew_concat(x, N, S, E, W):
    """Pad x with zeros to the north, south, east, and west."""
    k = len(x[0])
    stack = [[]]*N + x + [[]]*S
    return [([0]*W + [0]*(k - len(row)) + row + [0]*E) for row in stack]

关于python - 填充数组的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66487205/

相关文章:

python - 固定长度记录

python - 我怎样才能写一个没有重复的列表,只有 for,if 和 boolean

css 在列表项(导航栏)内填充图像

html - 填充顶部不起作用

html - .less 和 css "padding: @reference"

Python:两个二维数组的交集

python - Cython 文件是否会破坏社区版(免费)PyCharm?

android - 底部边距或填充在 android 上的 xml 中的相对布局中不起作用

c - 成员之间不会有填充是否安全?

python - 如何使用 pip 安装带有额外组件的本地 Python 包?