Home > Software engineering >  Storing values in a for loop in Python
Storing values in a for loop in Python

Time:06-18

I want to store values at each iteration through a for loop. The current and desired outputs are attached.

import numpy as np
from array import *
ar = []

A=np.array([[[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]],

       [[ 10,  11, 12],
        [ 13,  14,  15],
        [ 16,  17,  18]]])

for x in range(0,2):
    B=A[x] 1
    ar.append(B) 
print(ar)

The current output is

[array([[ 2,  3,  4],
       [ 5,  6,  7],
       [ 8,  9, 10]]), array([[11, 12, 13],
       [14, 15, 16],
       [17, 18, 19]])]

The desired output is

array([[[ 2,  3,  4],
        [ 5,  6,  7],
        [ 8,  9,  10]],

       [[11, 12, 13],
        [14, 15, 16],
        [17, 18, 19]]])

CodePudding user response:

@Ali_Sh's comment is correct, and the usage here is simply b = a 1, and that's that.

I will assume you are dumbing down some complicated use case which requires looping, so here is your code in a working form:

import numpy as np


a = np.array([[[1, 2, 3],
               [4, 5, 6],
               [7, 8, 9]],

              [[10, 11, 12],
               [13, 14, 15],
               [16, 17, 18]]])

ar = []
for x in range(0,2):
    b = a[x, :]   1
    ar.append(b)

print(np.stack(ar))


  • Related