In the first one you add the arrays of length 10 to the bigger array. So you need to create two arrays.
array1 = []
array2 = []
for j in range(20):
for i in range(10):
array1.append(0)
array2.append(array1)
array1 = []
print array2
This is equivalent to
array2=[[0 for j in range(10)] for i in range(20)]
Answer from Rolf Lussi on Stack OverflowTrying to create multiple arrays with different names using a for loop
Creating arrays with for and while loops - Python 2 - Stack Overflow
Creating new array in for loop (Python) - Stack Overflow
Assign values to array during loop - Python - Stack Overflow
Videos
Hi looking for help with a current project Iโm doing. I have a variable Number_Of_items which is an integer number read from a .txt file. Im trying to create a number of arrays equivalent to the variable Number_Of_items . For example if the value for Number_Of_items was 6, I would want to create 6 arrays with names array1, array2 , array3 etc. if anyone could point me in the right direction it would be appreciated.
In the first one you add the arrays of length 10 to the bigger array. So you need to create two arrays.
array1 = []
array2 = []
for j in range(20):
for i in range(10):
array1.append(0)
array2.append(array1)
array1 = []
print array2
This is equivalent to
array2=[[0 for j in range(10)] for i in range(20)]
You need to create a temporary list inside outer for/while loop which you can fill inside inner for/while loop.
First:
>>> for j in range(20):
... temp=[]
... for i in range(10):
... temp.append(0)
... array1.append(temp)
...
>>> array1
Second:
>>> count=0
>>> array3=[]
>>> while count < 20:
... temp=[]
... count_inner=0
... count+=1
... while count_inner< 10:
... temp.append(0)
... count_inner+=1
... array3.append(temp)
>>> array3
With your conditions in while loop check you were creating 21 X 11 matrix.
Why not try something like this to transpose the columns:
x = []
for d in xrange(0,66):
x.append(data[:,d])
Unless it's absolutely essential that there is a separate data structure for each item, although I don't know why you would need separate data strucures...
EDIT: If not here's something that should work precisely the way you described:
for d in xrange(1,68):
exec 'x%s = data[:,%s]' %(d,d-1)
As you show a little bit of the rpy code, I thought that I could show how it would look like with rpy2.
# build a DataFrame
from rpy2.robjects.vectors import IntVector
d = dict(('x%i' % (i+1), IntVector(data[:, i]) for i in range(68) if i != 9)
d['y'] = data[:, 9]
from rpy2.robjects.vectors import DataFrame
dataf = DataFrame(d)
del(d) # dictionary no longer needed
# import R's stats package
from rpy2.robjects.packages import importr
stats = importr('stats')
# fit model
dep_var = 'y'
formula = '%s ~ %s ' % (dep_var, '+'.join(x for x in dataf.names if x != dep_var))
linear_model = stats.lm(formula, data = dataf)
Appending elements while looping using append() is correct and it's a built-in method within Python lists.
However you can have the same result:
Using list comprehension:
result_t = [k for k in range(1,6)]
print(result_t)
>>> [1, 2, 3, 4, 5]
Using + operator:
result_t = []
for k in range(1,6):
result_t += [k]
print(result_t)
>>> [1, 2, 3, 4, 5]
Using special method __iadd__:
result_t = []
for k in range(1,6):
result_t.__iadd__([k])
print(result_t)
>>> [1, 2, 3, 4, 5]
The range function returns an iterator in modern Python. The list function converts an iterator to a list. So the following will fill your list with the values 1 to 5:
result_t = list(range(1,6)) # yields [1, 2, 3, 4, 5]
Note that in order to include 5 in the list, the range argument has to be 6.
Your last example doesn't parse unless you assign t a value before the loop. Assuming you do that, what you're doing in that case is modifying t each time through the loop, not just producing a linear range. You can get this effect using the map function:
t = 0
b = 2
def f(i):
global t
t = i + b*t
return t
result_b = list(map(f, range(1, 5))) # Yields [1, 4, 11, 26]
The map function applies the f function to each element of the range and returns an iterator, which is converted into a list using the list function. Of course, this version is more verbose than the loop, for this small example, but the technique itself is useful.
variable = []
Now variable refers to an empty list*.
Of course this is an assignment, not a declaration. There's no way to say in Python "this variable should never refer to anything other than a list", since Python is dynamically typed.
*The default built-in Python type is called a list, not an array. It is an ordered container of arbitrary length that can hold a heterogenous collection of objects (their types do not matter and can be freely mixed). This should not be confused with the array module, which offers a type closer to the C array type; the contents must be homogenous (all of the same type), but the length is still dynamic.
This is surprisingly complex topic in Python.
Practical answer
Arrays are represented by class list (see reference and do not mix them with generators).
Check out usage examples:
# empty array
arr = []
# init with values (can contain mixed types)
arr = [1, "eels"]
# get item by index (can be negative to access end of array)
arr = [1, 2, 3, 4, 5, 6]
arr[0] # 1
arr[-1] # 6
# get length
length = len(arr)
# supports append and insert
arr.append(8)
arr.insert(6, 7)
Theoretical answer
Under the hood Python's list is a wrapper for a real array which contains references to items. Also, underlying array is created with some extra space.
Consequences of this are:
- random access is really cheap (
arr[6653]is same toarr[0]) appendoperation is 'for free' while some extra spaceinsertoperation is expensive
Check this awesome table of operations complexity.
Also, please see this picture, where I've tried to show most important differences between array, array of references and linked list:
