无法在 2 列表匹配程序中进行循环比较和打印所需的元素

Cannot make loops in a 2-list matching program compare and print needed elements

我在一个 2 列表匹配程序中制作循环时遇到问题,该程序比较并打印出出现在两个列表中的所需元素索引。

word = "Hello"

consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z']

for character in range(len(word)): 
    for char in range(len(consonants)): 
        if consonants[char] == word[character]: 
            consonant = word[character]
            print consonant

程序通过遍历 word 然后遍历包含所有可能辅音的 consonants 列表来确定辅音是否存在于字符串中,测试 [=12 的当前元素是否存在=] 匹配 consonants 列表中的一个元素。

输出应该是每个辅音元素的索引,但我得到的是:

1
1

我做错了什么?

使用列表理解

>>>> [ind for ind, letter in enumerate(word) if letter.lower() in consonants]
[0, 2, 3]

The output should be the index of each element that is a consonant

哪个索引?如果你的意思是索引到辅音,那么:

>>> [consonants.index(c) for c in word.lower() if c in consonants]
[5, 8, 8]

如果效率很重要,请使用两个步骤:

>>> d = dict((char, i) for (i, char) in enumerate(consonants))
>>> [d[c] for c in word.lower() if c in consonants]
[5, 8, 8]

这段代码怎么样

word = "Hello"

consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p',
            'q', 'r', 's', 't', 'v', 'w', 'x', 'z']

for char in word.lower():
    if char in consonants:
        print consonants.index(char),

输出:5 8 8

我在单词上使用了 lower,因为在辅音列表中找不到大写 'H'。