【问题标题】:Expand Array w/ duplicates (numpy, python)展开带有重复项的数组(numpy,python)
【发布时间】:2021-12-03 07:45:07
【问题描述】:

如果我有一个像这样的 2 x 2 数组:

1   2

3   4

我想将它加倍成一个 4 x 4 数组,如下所示:

1   1   2   2
1   1   2   2
3   3   4   4
3   3   4   4

或将其三倍成 6 x 6 数组,如下所示:

1   1   1   2   2   2
1   1   1   2   2   2
1   1   1   2   2   2
3   3   3   4   4   4
3   3   3   4   4   4
3   3   3   4   4   4

等等等等……我该怎么做呢?

【问题讨论】:

标签: python arrays numpy matrix


【解决方案1】:

不确定这是否是最好的解决方案,但绝对有效 =p (你也可以只用一个函数,我把它分开以便于阅读)

matrix = [[1, 2], [3, 4]]


def expand_array(input, multiplyer):
    return [x for x in input for _ in range(multiplyer)]


def expand_matrix(input, multiplyer):
    return [expand_array(x, multiplyer) for x in input for _ in range(multiplyer)]


print(matrix)
print(expand_matrix(matrix, 1))
print(expand_matrix(matrix, 2))
print(expand_matrix(matrix, 3))
print(expand_matrix(matrix, 4))

"""
[[1, 2], [3, 4]]
[[1, 2], [3, 4]]
[[1, 1, 2, 2], [1, 1, 2, 2], [3, 3, 4, 4], [3, 3, 4, 4]]
[[1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 2, 2], [3, 3, 3, 4, 4, 4], [3, 3, 3, 4, 4, 4], [3, 3, 3, 4, 4, 4]]
[[1, 1, 1, 1, 2, 2, 2, 2], [1, 1, 1, 1, 2, 2, 2, 2], [1, 1, 1, 1, 2, 2, 2, 2], [1, 1, 1, 1, 2, 2, 2, 2], [3, 3, 3, 3, 4, 4, 4, 4], [3, 3, 3, 3, 4, 4, 4, 4], [3, 3, 3, 3, 4, 4, 4, 4], [3, 3, 3, 3, 4, 4, 4, 4]]
"""

【讨论】:

    【解决方案2】:

    你可以使用np.repeat:

    
    a = [[1,2],
         [3,4]]
    
    dim_expand = 2 # double
    
    b = np.repeat(a, dim_expand, axis=0).repeat(dim_expand, axis=1)
    
    print(b)
    
    """
    [[1 1 2 2]
     [1 1 2 2]
     [3 3 4 4]
     [3 3 4 4]]
    
    """
    
    dim_expand = 3 # triple
    
    b = np.repeat(a, dim_expand, axis=0).repeat(dim_expand, axis=1)
    
    print(b)
            
    """
    [[1 1 1 2 2 2]
     [1 1 1 2 2 2]
     [1 1 1 2 2 2]
     [3 3 3 4 4 4]
     [3 3 3 4 4 4]
     [3 3 3 4 4 4]]
    """
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-09
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      • 2014-05-21
      • 1970-01-01
      • 2022-01-19
      相关资源
      最近更新 更多