【问题标题】:list comprehension containing enumerate equivalent in javascript列表理解包含 javascript 中的枚举等价物
【发布时间】:2021-11-09 15:21:39
【问题描述】:

请问这个python代码在javascript中的等价物是什么

guessed_index = [
        i for i, letter in enumerate(self.chosen_word)
        if letter == self.guess
    ]

枚举和列表理解在 ES6 等效项中不存在,我如何将这两种想法合二为一

【问题讨论】:

  • 列表推导只是经典循环的语法糖,你当然可以做到这一点;)关于枚举,你可以简单地设置一个在循环的每一步都增加的计数器

标签: javascript python list-comprehension enumerate


【解决方案1】:

关注问题的 iterable/enumerate 部分,而不是您正在执行的特定任务:您可以使用 generator function 实现 Python's enumerate 的 JavaScript 模拟,并使用生成的生成器(这是可迭代的超集)通过for-of(或手动,如果您愿意):

function* enumerate(it, start = 0) {
    let index = start;
    for (const value of it) {
        yield [value, index++];
    }
}

const word = "hello";
const guess = "l";
const guessed_indexes = [];
for (const [value, index] of enumerate(word)) {
    if (value === guess) {
        guessed_indexes.push(index);
    }
}
console.log(`guessed_indexes for '${guess}' in '${word}':`, guessed_indexes);

或者您可以编写一个特定的生成器函数来执行查找匹配项的任务:

function* matchingIndexes(word, guess) {
    let index = 0;
    for (const letter of word) {
        if (letter === guess) {
            yield index;
        }
        ++index;
    }
}

const word = "hello";
const guess = "l";
const guessed_indexes = [...matchingIndexes(word, guess)];

console.log(`guessed_indexes for '${guess}' in '${word}':`, guessed_indexes);

【讨论】:

    【解决方案2】:

    也许findIndex 有用?

    const word = "Hello";
    const guess = "o";
    const guessed_index = [...word].findIndex(letter => letter === guess);
    console.log(guessed_index)
        

    【讨论】:

      【解决方案3】:

      为了让不精通 Python 的潜在读者更清楚,下面是与您的理解等效的 Python 循环:

      guessed_index = []
      i = 0
      for letter in self.chosen_word:
          if letter == self.guess:
              guessed_index.append(i)
          i += 1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-22
        • 1970-01-01
        • 1970-01-01
        • 2011-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-18
        相关资源
        最近更新 更多