Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
152
rated 0 times [  155] [ 3]  / answers: 1 / hits: 20932  / 6 Years ago, fri, may 11, 2018, 12:00:00

I am trying to re-write some Python code to Javascript.



I can't figure out how to rewrite this part :



zone_indices = [[idx for idx, val in enumerate(classified) if zone + 1 == val] for zone in range(maxz)]


idx for idx, val : what does it mean to put idx at the beginning ?


More From » python

 Answers
4

idx is usually short for index.



Python loops allows items in a nested list to be accessed directly like so:



>>> lst = [[1, 2], [3, 4], [5, 6]]
>>>
>>> for a,b in lst:
print a,b

1 2
3 4
5 6


Using enumerate in Python allows for something similar:



>>> for idx,val in enumerate(['a','b','c']):
print('index of ' + val + ': ' + str(idx))

index of a: 0
index of b: 1
index of c: 2


The equivalent of enumerate(array) in JavaScript is array.entries(), and can be used in much the same way as Python:



zone_indices = []

for (let i = 0; i < maxz.length, i++) {
for (let [idx, val] of classified.entries()) {
if (zone+1 === val) {
zone_indices.push(idx);
};
};
};

[#54460] Tuesday, May 8, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jackie

Total Points: 442
Total Questions: 107
Total Answers: 94

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
jackie questions
Sat, Sep 18, 21, 00:00, 3 Years ago
Wed, Jul 14, 21, 00:00, 3 Years ago
;