Reputation: 15
I have this line in python for list comprehension, however I don't understand much of this language, and I wanted to convert it to javascript.
the line is:
next = [ (i,j) for i,j in getValidMoves(grid,x,y,moves) ]
num = [ (len(getValidMoves(grid,x+i,y+j,moves)),i,j) for i,j in next]
getValidMoves is an auxiliary function, but i think it is not necessary to understand the rest of the code
Upvotes: 0
Views: 139
Reputation: 675
3 things that might help you convert this into Javascript:
for...in
loops.for...in
loop would be a for...of
loop. The for...in
loop in JavaScript does something different. (It's JavaScript, so for (var i = 0; ...; ++i) ...
can also be used though.)for i, j in ...
is called "unpacking" in Python; equivalent to "Destructuring assignment" in JavaScript.Upvotes: 1
Reputation: 1937
Let's start with how a for loop in python works:
In contrast with many languages, python actually takes each element contained in whatever iterable object you give in the foor loop statement, and is iterating through that object without any incrementation whatsoever. So in python the following code is not an endless loop.
for i in range(5):
i=3
print(i)
## prints 3, five times
All this gives the ability to the for loop to iterate through an iterable like the following
for i in ['hsusu', 4, ['usjs'], '21']:
print(i)
## prints each one of the list elements
Now the for loop inside the list comprehension is the same thing as a normal for loop. However the list comprehension is a fast way of creating lists from iterables because it using the append function efficiency. In the following example with a normal multiline for loop you are using append 5 times in order to create a list
next = [] # an empty list
for i, j in getValidMoves(grid,x,y,moves): # iterate through the iterable
next.append((i,j)) # append the desired element
In the contrary, list comprehension doesn't call the append function ( or at least not so much. I am not sure), so the iteratyion is completed faster.
About next = [ (i,j) for i,j in getValidMoves(grid,x,y,moves)]
This line is creating a list, because of the square brackets, named next
, because of the variable name, that contains tuples, because of the normal brackets of (i,j), out of the contents of the output of the function getValidMoves(grid,x,y,moves)
, which should be an iterable (otherwise there will be an error). Now since you are using two variables in the for loop the iterable has to be something like [[1,2],[7,8]], where each elemen6 of the iterable is an iterable with 2 elements.
l hope that you understand everything now and if not tell in the comments what should I explain better. I will soon add references for everything I wrote.
Upvotes: 2