简体   繁体   English

Python循环:idx用于idx(重写为javascript)

[英]Python loop : idx for idx (rewrite to javascript)

I am trying to re-write some Python code to Javascript. 我正在尝试将一些Python代码重写为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用于val的idx :将idx放在开头是什么意思?

"idx" is usually short for index. “ idx”通常是索引的缩写

Python loops allows items in a nested list to be accessed directly like so: Python循环允许像这样直接访问嵌套列表中的项目:

>>> 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: 在Python中使用枚举可实现以下类似功能:

>>> 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: JavaScript中的enumerate(array)等效于array.entries() ,并且可以与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. 但是,如果您需要项的值和索引 ,则可能要使用带有可迭代的enumerate 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. 在这里,在for关键字的左侧,您可以任意顺序使用ixval或两者。 But at the right side val always should follow the ix . 但是在右侧, val始终应遵循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)
        }
    } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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