Home > Blockchain >  Python Equivalent to Javascript index assignment
Python Equivalent to Javascript index assignment

Time:07-02

Original code in JS:

// applying crossover
for (let i = cxpoint1; i < cxpoint2; i  ) {
  let temp1 = ind1[i]
  let temp2 = ind2[i]

  ind1[i]         = temp2
  ind1[p1[temp2]] = temp1

  ind2[i]         = temp1
  ind2[p2[temp1]] = temp2

  return [ind1, ind2]

New to JS and wondering what is happening on this line:

ind1[p1[temp2]] = temp1

Trying to understand so I can make an equivalent function in Python.

I understand the assignment, however obviously in Python you cannot use double brackets as shown on the line above. If someone could tell me the concept, I should be able to apply it to my situation.

Thanks in advance.

CodePudding user response:

To fully understand the code one would need to know how the arrays p1 and p2 look like, but I assume they are integer-arrays. You select an integer from that array in the inner statement that then is the index for the outer statement.

It works exactly the same in python:

ind1 = [1, 2, 3, 4, 5]
p1 = [3, 1, 2]
print(ind1[p1[0]])
# -> 4

In this example the inner statement resolves to 3 (first element in the p1-list) and the outer statement then resolves to 4 (fourth element in the ind1-list.

CodePudding user response:

There's nothing magical going on here.

ind1[p1[temp2]]

p1[temp2] resolves to some value, let's call it a. So the expression then becomes ind1[a].

  • Related