Store Values in for Loop

How to store values in a vector inside a for loop in R

You can use append() to add an element to the end of a vector:

my_vector <- vector(mode="numeric")

number <- 80:84

for(i in number) {
#insert the calculation here, let's say it is i+3
result <- i+3
my_vector <- append(my_vector, result)
}

Note: You don't need to use a for loop for this. Since the addition operator in R is vectorized, you can just do:

my_vector <- number + 3

Storing values in a for loop in Python

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

store value of for loop iteration into single variable (Python)

You are overwriting words in the loop.

Set it to the empty string before the loop, then use the += operator to concatenate to the variable rather than overwriting the previous values.

words = ''
for i in range(len(ticket_json)):
...
ticketsubject_str = ...
ticketstatus_str = ...
ticketcreationdate = ...
ticketupdateddate = ...
ticketstatusreplace_str = ...
words += (...)

Store values generated by a for-loop. JuMP/Julia

You didn't initialize vector and you should call the method println like this following way, in Julia 1.0 :

vector = Array{Int,1}(undef, 5)
for i in 1:5
vector[i] = i
println(vector[i])
end

Or, more quickly, with a comprehension list :

vector = [i for i in 1:5]
for i in 1:5
println(vector[i])
end

Another possibility using push! method :

vector = []
for i in 1:5
push!(vector, i)
println(vector[i])
end

How can i store data in an automatically created variable inside a for-loop?

You can not name a different variable at each loop iteration, but you can store them in a dict {}:

button = {}
def initButtons(partlist : list, path : str):
buttonsToLoad = ['ButtonActive1.png', 'ButtonInactive1.png', 'ButtonClicked1.png']
for x in partlist:
button[str(x) + '0'] = Image.open(f'{path}/{x}/{buttonsToLoad[0]}')
button[str(x) + '1'] = Image.open(f'{path}/{x}/{buttonsToLoad[1]}')
button[str(x) + '2'] = Image.open(f'{path}/{x}/{buttonsToLoad[2]}')

Then you can access your Image simply by searching its name in the dict's keys:

image = button['apple0']  # if its name is 'apple' + '0'


Related Topics



Leave a reply



Submit