I have some code of which I obtain an array of different values within a double for loop. I assign it to a list test
and I want to set them one by one on this matrix of 8 x 8
I have tried:
for i in range(8):
for j in range(8):
matrixc[i][j] = testi[i]
I want to have a different value on each tuple. How can I advance through the list on each iteration?
Is this what you are looking for?
for i in range(8):
for j in range(8):
matrixc[i][j] = testi[i*8 + j]
Alternatively:
for index, element in enumerate(testi):
matrixc[index / 8][index % 8] = element
If you're pulling from a linear array then you could access it using array[i*8 + j] instead of array[i]
Related
n = 5
k = 6
matrix = [[j for i in range(n)] for j in range(k)]
for element in matrix[3]:
print(element)
element = 100
print(matrix)
I expect to see one row in my matrix to be all 100 at the end, but the values are all still initial values, why is this happening?
When you run:
for element in matrix[3]:
element = 100
all you're doing is changing the element inside the for loop. When another round of the for loop starts, element is changed back to what it should be, i.e.: the next element in the matrix. You can think of element as a temporary variable that changes every run of the loop.
More importantly, 'element' is now separate from the matrix. Changing 'element' will not change the matrix. You need to directly call on the matrix element you want to change and assign it whatever value you want to set it to. The proper way to do this would be to do:
for i in range(len(matrix[3])):
matrix[3][i] = 100
Check the code below for what the right code should look like.
n = 5
k = 6
matrix = [[j for i in range(n)] for j in range(k)]
for i in range(len(matrix[3])):
matrix[3][i] = 100
print(matrix)
i do learn Python for scientific working. At the moment i try to generate a 10x10 random Matrix with binary entries: 0 and 1. I already got a solution with numpy BUT im interested of what is the error in my own solution.
The Idea is to Access every entry of my Matrix seperately and assign a value to it by calling random.randint(0, 1 ) within two while loops. In Advance i define a dummy 10x10 Matrix called "World" and reassign ist values it in the loop. The Code Looks how follows:
import random
World=list(10*[10*[0]]) #this is my dummy matrix
i=0
j=0
while i <= 9:
while j <= 9:
World[i][j]=random.randint(0, 1) #here i want to Access a specific element of my dummy Matrix and "overwrite" it
if j == 9:
j=0 #if the counter "j" reaches 9 - the last element - it shall assign j=0 and leave the innermost while loop by "break"
break
j=j+1
i=i+1
for x in World:
print(*x)
The Problem with the Output should be obvious:
columns are equal
I am hopefully u understand what was my Intention here and can help me fix my code. I tried many many Things but i did not fix this.
I already found a 2-line short solution which i will use in my final Code but i want to run this also on my own because i am convinced this could work also well.
Many Thanks in Advance.
- Wendel
Your error is in the creation of the list.
NOTE:
[0] * m returns just a reference to a list of m zeros, but not a list.
The subsequent repeating of this element creates a list of n items
that all reference to the same list (just as well as the operation b =
a for lists does not create the new list), so all rows in the
resulting list are actually the same string.
import random
#World=list(10*[10*[0]]) #this is my dummy matrix
n = 10
World= [0] * n
for i in range(n):
World[i] = [0] * n
i=0
j=0
while i <= 9:
while j <= 9:
World[i][j]=random.randint(0, 1) #here i want to Access a specific element of my dummy Matrix and "overwrite" it
if j == 9:
j=0 #if the counter "j" reaches 9 - the last element - it shall assign j=0 and leave the innermost while loop by "break"
break
j=j+1
i=i+1
for x in World:
print(*x)
Suppose that two numbers are given: the number of rows of n and the number of columns m. You must create a list of size n×m, filled with, say, zeros.
The obvious solution appears to be wrong:
a = [[0] * m] * n
This can be easily seen if you set the value of a[0][0] to 5, and then print the value of a[1][0] — it will also be equal to 5. The reason is, [0] * m returns just a reference to a list of m zeros, but not a list. The subsequent repeating of this element creates a list of n items that all reference to the same list (just as well as the operation b = a for lists does not create the new list), so all rows in the resulting list are actually the same string.
n = 3
m = 4
a = [[0] * m] * n
a[0][0] = 5
print(a[1][0])
A possible way: you can create a list of n elements (say, of n zeros) and then make each of the elements a link to another one-dimensional list of m elements:
n = 3
m = 4
a = [0] * n
for i in range(n):
a[i] = [0] * m
Another (but similar) way: create an empty list and then append a new element to it n times (this element should be a list of length m):
n = 3
m = 4
a = []
for i in range(n):
a.append([0] * m)
But the easiest way is to use generator, creating a list of n elements, each of which is a list of m zeros:
n = 3
m = 4
a = [[0] * m for i in range(n)]
In this case each element is created independently from the others. The list [0] * m is n times consructed as the new one, and no copying of references occurs.
for i in range(x):
for j in range(y):
for k in range(z):
if arr[i][j][k] != 0:
arr[i][j][k] = 1
I'm traversing through a 3D array and if any value is not equal to 1, I would like to change it to 1.
If you use numpy, just write:
arr[arr!=0] = 1
or if you only need a boolean array:
result = arr!=0
If you, on the other side, have a list of list of lists:
for plane in arr:
for row in plane:
row[:] = [int(item!=0) for item in row]
I have a 2d array with a different species in each one. I pick a random element on the array and I want to count up how many of each species are in the eight squares immediately adjacent to that element.
But I want the array to wrap at the edges, so if I pick an element on the top row, the bottom row will be counted as "adjacent". How can I do this while iterating through j in range (x-1,x+1) and the same for j and y?
Also, is there a more elegant way of omitting the element I originally picked while looking through the adjacent squares than the if (j!=x or k!=y line?
numspec = [0] * len(allspec)
for i in range (0,len(allspec)):
#count up how many of species i there is in the immediate area
for j in range(x-1,x+1):
for k in range(y-1,y+1):
if (j!=x or k!=y):
numspec[hab[i][j]] = numspec[hab[i][j]]+1
You can wrap using j%8 that gives you a number from 0 to 7.
As for wrapping, I would recomend using relative indexing from -1 to +1 and then computing real index using modulo operator (%).
As for making sure you don't count the original element (x, y), you are doing just fine (I would probably use reversed contidion and continue, but it doesn't matter).
I don't quite understand your usage of i, j, k indexes, so I'll just assume that i is index of the species, j, k are indexes into the 2d map called hab which I changed to x_rel, y_rel and x_idx and y_idx to make it more readable. If I'm mistaken, change the code or let me know.
I also took the liberty of doing some minor fixes:
introduced N constant representing number of species
changed range to xrange (xrange is faster, uses less memory, etc)
no need to specify 0 in range (or xrange)
instead of X = X + 1 for increasing value, I used += increment operator like this: X += 1
Here is resulting code:
N = len(allspec)
numspec = [0] * N
for i in xrange(N):
for x_rel in xrange(-1, +1):
for y_rel in xrange(-1, +1):
x_idx = (x + xrel) % N
y_idx = (y + yrel) % N
if x_idx != x or y_idx != y:
numspec[hab[x_idx][y_idx]] += 1
You could construct a list of the adjacent elements and go from there. For example if your 2d list is called my_array and you wanted to examine the blocks immediately surrounding my_array[x][y] then you can do something like this:
xmax = len(my_array)
ymax = len(my_array[0]) #assuming it's a square...
x_vals = [i%xmax for i in [x-1,x,x+1]]
y_vals = [blah]
surrounding_blocks = [
my_array[x_vals[0]][y_vals[0]],
my_array[x_vals[0]][y_vals[1]],
my_array[x_vals[0]][y_vals[2]],
my_array[x_vals[2]][y_vals[0]],
my_array[x_vals[2]][y_vals[1]],
my_array[x_vals[2]][y_vals[2]],
my_array[x_vals[1]][y_vals[0]],
my_array[x_vals[1]][y_vals[2]],
]
I have a vector with int values like:
v=[10,8,6]
and what I want is to create an m*m matrix that stores the distance between these elements, i.e. take each element of the vector and substract it from all the other ones, so at the end I will end up with:
m[3][3]=10-10 10-8 10-6
8-10 8-8 8-6
6-10 6-8 6-6
I want to implement it into Python, but without using NumPy. I have done this so far:
def main():
v=[10,8,6]
l=len(v)
m=[]
#filling the matrix
for i in range(0,l-1):
for j in range(0,l-1):
m[i][j]=abs(v[i]-v[j])
#visualize the matrix
for i in range(0,l-1):
for j in range(0,l-1):
print m[i][j]
But I am getting some error that does not recognize with the bounds of m. Why is that?
v= [10,8,6]
m = [[abs(y-x) for y in v] for x in v]
EDIT:
For pretty printing you can use something like:
for i in m:
print '%s '*len(i) % tuple(i)
You need to make a list for each row inside of the enveloping list. I used a double list comprehension to make m and then made the formatting a little prettier for printing out the matrix. Also, watch your indices: remember that range goes from the first index to one minus the second index passed to it. You could also do print ' '.join(row) for each row in m to print it out nicely.
def main():
v=[10,8,6]
l=len(v)
#filling the matrix
m=[[abs(x - y) for y in v] for x in v]
#visualize the matrix
for i in range(0,l):
for j in range(0,l):
print m[i][j],
print
main()
result:
0 2 4
2 0 2
4 2 0
Your list starts out empty. You can't index the element in the list. One way to solve this would be to create the lists and then append them.
m=[]
#filling the matrix
for i in range(0,l-1):
x = []
for j in range(0,l-1):
x.append( abs(v[i]-v[j]) )
m.append(x)
Or you could create the matrix and then fill it up
m=[[0] *l for x in range(l)]
#filling the matrix
for i in range(0,l-1):
for j in range(0,l-1):
m[i][j]=abs(v[i]-v[j])
better yet is the list comprehension other have shown
m = [[abs(y-x) for y in v] for x in v]
but then, I'd use numpy/scipy
m = scipy.spatial.distance.pdist(v)
You need to initialize each object in the first dimension as an array, otherwise it's like you're basically trying to index on None.
#filling the matrix
for i in range(0,l-1):
m[i] = []
for j in range(0,l-1):
m[i][j]=abs(v[i]-v[j])