could someone give me some ideas of what I can do with this code? The user will give a number of values as an argument, and the shape will be the dimensions of the list.
The problem here I is with the v variable, I want to use the v variable to index the values(list) so I can change the nth dimension of the list, so for example.
In the example under where i do v m, I want the index to not start for 0 where i get the value 1 from the value list, but to get the value 5, but I cant find a solution to do this since i need to define v at the start with 0 and check if its not 0.
Any help is appreciated. ps. I dont want to use any numpy arrays or anything other than lists
def test(shape , *values):
n = shape[1]
m = shape[0]
nDim = [[0 for column in range(m)] for row in range(n)]
values = list(values)
for x in range (n):
print(x)
v = 0
if(v%m == 0):
v =m
for y in range (m):
nDim[x][y] = values[v]
v = 1
return nDim
m = test((4,2) , 1, 2 ,3, 4 , 5 ,6 , 7 , 8)
CodePudding user response:
You are quite close!
It's true you need to set v=0
but you should do that only once, before the first loop, so you won't reset it between loops. And then your modulo condition is not needed at all, as you increment v
in every iteration so choose every *values
element once.
v = 0
for x in range(n):
for y in range(m):
nDim[x][y] = values[v]
v = 1
You could even omit v
as it can be calculated from x
and y
nDim[x][y] = values[x * m y]
CodePudding user response:
I would do it like this:
def to_list_of_lists(shape, *values):
values = list(values)
result = []
for row in range(shape[1]):
start_index = row * shape[0]
stop_index = start_index shape[0]
result.append(values[start_index:stop_index])
return result
x = to_list_of_lists((4,2) , 1, 2 ,3, 4 , 5 ,6 , 7 , 8)