Taio
Taio

Reputation: 1

Running through variables in for loop

I'm new to Python, but I use it to process data. I've got a large amount of data stored as float arrays:

data1
data2
data3

I want to run similar processing for each data file. I was thinking of using a for loop:

for i in range(1,4):

I would like to then multiply the three data files by two, but I'm not sure how to continue afterwards. I imagine it would look like his:

for i in range(1,4):
     data_i=data_i*2

Thank you.

Upvotes: 0

Views: 90

Answers (3)

rook
rook

Reputation: 6270

You could also use Python comprehension instead of loops, here is an example to illustrate it:

>>> a1 = [1,2,3]
>>> a2 = [4,5,6]
>>> a3 = [7,8,9]
>>> A = [a1, a2, a3]
>>>
>>> print [[x*2 for x in a] for a in A]
[[2, 4, 6], [8, 10, 12], [14, 16, 18]]
>>>

Let me explain it also.

The following construction is called comprehension:

a = [x*2 for x in X]

It produces an array (as you could see the brackets [ ]) of processed values (in the example value multiplication by two) from array X. It's as if we wrote:

a = []
for x in X:
    a.append(x*2)

but in more concise way. In your situation we used two comprehension one in one:

[x*2 for x in a]

and:

[ [....] for a in A]

So it's the same as if we did:

result = []
for a in A:
    for x in a:
        result.append(x*2)

but in more concise way again.

 

If you asked about variable names modification, so it is not possible in the Python without altering the language processor. But I guess you don't need it in that task at all.

Upvotes: 0

Jendas
Jendas

Reputation: 3589

You can simply store the data in e.g. list

data_list = [data1, data2, data3]

for i, data in enumerate(data_list):
    some_fancy_stuff
    data_list[i] = data * 2

Some explanation - enumerate will literally enumerate the items of the list with index i and also assigns data_list[i] to variable data. Than you can do whatever you want with data and its index i.

Upvotes: 0

Lars de Bruijn
Lars de Bruijn

Reputation: 1518

You could make a two-dimensional array, meaning you put your float arrays inside another array.

Your situation right now would look like this:

data1 = [12, 2, 5]
data2 = [2, 4, 8]
data3 = [3, 0, 1]

By putting your arrays inside another array by doing this:

datax = [data1, data2, data3]

Your new situation would look like this:

datax = [[12, 2, 5], [2, 4, 8], [3, 0, 1]]

Now we can loop over the new datax array and perform an action on it's elements, data1, data2 and data3.

Something along the lines of:

datax = [[12, 2, 5], [2, 4, 8], [3, 0, 1]]

for sub_array in datax:
    perform_action(sub_array)

Upvotes: 1

Related Questions