我正在尝试将一些 Python 代码重写为 Javascript。
我不知道如何重写这部分:
zone_indices = [[idx for idx, val in enumerate(classified) if zone + 1 == val] for zone in range(maxz)]
Run Code Online (Sandbox Code Playgroud)
idx for idx, val:将idx放在开头是什么意思?
“idx”通常是索引的缩写。
Python 循环允许直接访问嵌套列表中的项目,如下所示:
>>> lst = [[1, 2], [3, 4], [5, 6]]
>>>
>>> for a,b in lst:
print a,b
1 2
3 4
5 6
Run Code Online (Sandbox Code Playgroud)
在 Python 中使用 enumerate 允许类似的事情:
>>> 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
Run Code Online (Sandbox Code Playgroud)
enumerate(array)在 JavaScript 中的等价物是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);
};
};
};
Run Code Online (Sandbox Code Playgroud)