简体   繁体   中英

Python loop : idx for idx (rewrite to javascript)

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 ?

"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);
        };
    };
};

Let's say you have an iterable and you want to iterate over it and you need only values of its items. You can use ordinary list comprehension:

[x for x in it]

But if you need value and index of an item, you probably want to use enumerate with iterable. And in this case it will look like this:

[(ix, val) for ix, val in it]

Here, at the left side of for keyword you may take ix , val or both in any order. But at the right side val always should follow the ix .

Your code :

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

is equivalent to this:

zone_indices = []

for zone in range(maxz):
    for idx, val in enumerate(classified):
         if zone + 1 == val:
            zone_indices.append(idx)

I think now it must be easy to covert to it JS. It may be something like below:

zone_indices = []
for(let zone=0; zone< maxz ; zone++){
    for(idx in classified){
        if (zone + 1 === classified[idx]){
            zone_indices.push(idx)
        }
    } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM