简体   繁体   中英

Storing values in a for loop in Python

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]]])

@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))


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM