I'm trying to create a bidimensional array using list comprehension.
a = [[0 for y in range(1, 10)] for x in range(1, 10)]
This should create a 9x9 'matrix' whose first item is a[1][1], and last is a[9][9]
However this is not happening, and when I try to print the last element:
print(a[9][9])
I get an out of range error.
What am I doing wrong?
You do have a 9x9 matrix (or list of lists), but since indices are zero based, you can only index from 0 to 8 along both axes.
The start value 1 in the range function does not influence the start value of your indexing; it will always be zero.
Related
I need to create an List of size N and then initialize only N-1th and N-2th elements only. Which means if the size of the list is 5 then it should only contain elements in 3rd and 4th position.
i know how to do it in C++ but is there any way to implement it in Python?
for example: In C++
int *n = new int[5];
n[3] = 20
n[4] = 10
//and if we print the output it will show some garbage values in index 0, 1, 2 and will print 20 10 which is the values we initailized
How can i do it in python? or anything similar to this!
In python, list must be initialized with values.
Closest thing you can do:
N = 5
lst = [0] * (N-2) + [20, 10]
This:
Fills the N-2 elements of a list with default value 0
Sets the value for the last two elements
Concatenates the zeros and last two elements sub-lists of stages 1 & 2
In python,
array=[]
length=5
for i in range(length):
array.append(0)
array[3]=20
array[4]=10
Edit: As pointed out by kabanus, a more efficient way to do this would be-
array=[0]*length
Instead of the for loop.
I am pretty new to python, i am using python 3 and have some difficulties to append the result of the iteration to the array, following is my chunk of my code:
A = np.random.randn(len(meas),numx)
lengthA = np.linspace(0,len(A[0])-1,num=len(A[0]),dtype=int)
anorm = []
for j in range(0,len(lengthA)):
x_normed = A/A.max(axis=0)
anorm[:,j] = A[:,j]*x_normed[j]
Is it necessary to append the new result to empty anom ? somehow the code always tell me that the list of the indices must be integer and not tuple. Any help will be appreciated.
When assigning a value to an array at index n via the array[index] = value syntax, the argument within the square brackets must be an integer. In your situation, j is an integer but [:,j] attempts to reference multiple indices within the array.
for j in range(0,len(lengthA)):
x_normed = A/A.max(axis=0)
anorm[j] = A[:,j]*x_normed[j]
As an aside, if you want your for loop to run for as many iterations as there are elements within lengthA, then you can simply do:
for j in lengthA:
do stuff
I have a numpy array of floats that I want to reassign with a different value using a for loop but PyCharm says the new variable assignment isn't being used.
If I have, say:
for i in array:
i = i * 5
It will say that i is an unused variable. What am I doing wrong?
You need to assign values to array elements. Otherwise you array will remain unchanged. There are a couple of ways.
Using your current attempt as a starting point, you can use enumerate. Given an input array:
for idx, val in enumerate(array):
array[idx] = val * 5
But this doesn't take advantage of NumPy vectorisation. You can simply use:
array *= 5
Should be:
for i in range(len(array)):
array[i] = array[i] * 5
What you did was creating a temporary variable "i", which exists only on each loop iteration, it is initialized with the value of an element from the list and then it's deleted.
A more pythonic way of doing this would be:
array = [i*5 for i in array]
I have a list called L. It has C number of elements.
I have a nd array called X. X has Boolean data (either 0 or 1). It has dimension as (20,C). There are 20 lists with each list having C number of elements
I want to locate each index that has value of 1 in X.Then I want the value at this same index in List L, and finally store this value from L in another nd array .
I write the following code
emptylist=[]
for index,value in np.ndenumerate(X): #this index is a tuple like (0,3)
tuple_to_list=list(i)
if value == 1:
emptylist.append (L[tuple_to_list[1]]) #error
the program does not stop running. Can you guide me to improve this code ?
the last line should be:
empylist.append(L[index[0]])
and I don't see what your tuple_to_list is needed for
A solution using only arrays would be the following:
L = list(np.random.rand(20)) # gives a List of radom values (to be compatible to the question)
La = np.array(L)
X = randint(0,5,(20,101)) # make an array having values from 0...4
emptylist = La[np.where(X==1)[0]] #gives those rows of L where rows of X contain 1
though the name empty is not appropriate anymore.
I have the following code
l = len(time) #time is a 300 element list
ll = len(sample) #sample has 3 sublists each with 300 elements
w, h = ll, l
Matrix = [[0 for x in range(w)] for y in range(h)]
for n in range(0,l):
for m in range(0,ll):
x=sample[m]
Matrix[m][n]= x
When I run the code to fill the matrix I get an error message saying "list index out of range" I put in a print statement to see where the error happens and when m=0 and n=3 the matrix goes out of index.
from what I understand on the fourth line of the code I initialize a 3X300 matrix so why does it go out of index at 0X3 ?
You need to change Matrix[m][n]= x to Matrix[n][m]= x
The indexing of nested lists happens from the outside in. So for your code, you'll probably want:
Matrix[n][m] = x
If you prefer the other order, you can build the matrix differently (swap w and h in the list comprehensions).
Note that if you're going to be doing mathematical operations with this matrix, you may want to be using numpy arrays instead of Python lists. They're almost certainly going to be much more efficient at doing math operations than anything you can write yourself in pure Python.
Note that indexing in nested lists in Python happens from outside in, and so you'll have to change the order in which you index into your array, as follows:
Matrix[n][m] = x
For mathematical operations and matrix manipulations, using numpy two-dimensional arrays, is almost always a better choice. You can read more about them here.