python - increase array size and initialize new elements to zero

后端 未结 3 418
小蘑菇
小蘑菇 2021-01-03 06:52

I have an array of a size 2 x 2 and I want to change the size to 3 x 4.

A = [[1 2 ],[2 3]]
A_new = [[1 2 0 0],[2 3 0 0],[0 0 0 0]]

I tried

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-03 07:01

    Pure Python way achieve this:

    row = 3
    column = 4
    A = [[1, 2],[2, 3]]
    
    A_new = map(lambda x: x + ([0] * (column - len(x))), A + ([[0] * column] * (row - len(A))))
    

    then A_new is [[1, 2, 0, 0], [2, 3, 0, 0], [0, 0, 0, 0]].

    Good to know:

    • [x] * n will repeat x n-times
    • Lists can be concatenated using the + operator

    Explanation:

    • map(function, list) will iterate each item in list pass it to function and replace that item with the return value
    • A + ([[0] * column] * (row - len(A))): A is being extended with the remaining "zeroed" lists
      • repeat the item in [0] by the column count
      • repeat that array by the remaining row count
    • ([0] * (column - len(x))): for each row item (x) add an list with the remaining count of columns using

提交回复
热议问题