- 1
Python for Loop Help: Why?
I know exactly what Iâm doing, Iâve printed it to the console so many times, yet I get the same results!!! https://code.sololearn.com/cN52Q2psjs0J/?ref=app I have a tuple of 3 lists, each list has 3 elements. I have a nested for loop: one iterates through the number of elements in the tuple the one inside iterates through each element in the listâor thatâs what it *should* do Iâve done massive amounts of debugging and it seems that the outside for loop just repeats 3 times while the inside loop just executes once! Itâs driving me crazy, please help. EDIT: output: [1, 2, 0], [2, 0, 1], [0, 1, 2] (Iâve put it in a comment under the original matrix)
9 RĂ©ponses
+ 4
You've three nested loops, and innermost one has a break. Iterating over a matrix should only require two.
Because of the break statement, the col variable is always 1 (after you do col+=1). arow becomes 2, 1, 0, in that order. So you're accessing the second column (2,0,3) in REVERSE order each time. The outermost loop with the columns variable is just doing it three times without any change.
What exactly do you want to do? Your sample matrix has too many repeats. Could you show it with this guy?
1 2 3
4 5 6
7 8 9
Also, this is not the transpose, which should look like
1 4 7
2 5 8
3 6 9
There we just interchange the rows with columns.
+ 3
Well, then please let me know once you're done editing. I am still unsure about your expected output.
+ 2
It's difficult to respond properly if you keep changing your code.
+ 1
What is the output supposed to be?
+ 1
This can probably be done a lot better, but I would try something like this:
tr = []
for i in range(len(matrix[0])):
tr.append([matrix[j][i] for j in range(len(matrix))])
Or simply
[[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
Or just use numpy's transpose function.
+ 1
7:01 am, 17 December, 2018 (GMT)
Currently your adjusted_row takes values 2, 1, 0, and for each value of adjusted_row, col takes values 0, 1, 2. So you're just appending elements in trow in this order (row, col):
(2,0), (2,1), (2,2), (1,0), (1,1), (1,2), (0,0), (0,1), (0,2)
You're also not adding new rows, so it's all one long list.
Anna's solution is perfect.
The basic idea is that the (i,j)-th entry of the transpose is the (j,i)-th entry of the original.
0
Iâve actually just worked it out, the output is right under the âmatrixâ variable at the top of the file, but Iâll paste it in here for convenience(Iâve also put it in the original question, thanks for the question):
[1, 2, 0],
[2, 0, 1],
[0, 1, 2]
0
yea, sorry, Iâm trying to figure it out too, i think its the break
0
Iâm done for the night