Reputation: 69
I'm trying to convert the following list comprehension to a normal for loop, mainly because I don't quite understand how it works yet:
board = [ [3 * j + i + 1 for i in range(3)] for j in range(3) ]
Creates a 2D array with values: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
My code:
board = []
for j in range(3):
for i in range(3):
board.append(3*j+i+1)
Creates a 1D array with values: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Upvotes: 2
Views: 975
Reputation: 569
In the same line guys (@RaySteam and @ansev) how can I rewrite this :
def bitStr(n,s):
if n==1:
return s
return [digit + bits for digit in bitStr(1,s) for bits in bitStr(n-1,s)]
print(bitStr(3,'123'))
Using two for loops ?
Upvotes: 0
Reputation: 30920
The internal loop saves values in the internal lists. The external loop stores the lists in the external list
board = []
for j in range(3):
board2=[]
for i in range(3):
board2.append(3*j+i+1)
board.append(board2)
print(board)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Explanation
simply in each cycle of the loop an element of the list is created. This is the simplest case:
[j for j in range(3)]
[0, 1, 2]
now in each cycle of the loop simply create a list with the index:
[[j] for j in range(3)]
[[0], [1], [2]]
Now we use the same mechanism to declare the internal list:
[[j for j in range(3)] for j in range(3)]
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
now we make the values of the internal lists depend on the external index:
[ [3 * j for i in range(3)] for j in range(3) ]
[[0, 0, 0], [3, 3, 3], [6, 6, 6]]
finally we increase depending on the internal index:
[ [3 * j + i + 1 for i in range(3)] for j in range(3) ]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Upvotes: 6
Reputation: 61910
You need to use an intermediate list to store the results:
board = []
for j in range(3):
row = []
for i in range(3):
row.append(3*j+i+1)
board.append(row)
print(board)
Output
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Upvotes: 5