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



我在一个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列表,测试word的当前元素是否与consonants列表的元素之一匹配,来识别字符串中是否存在辅音。

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

1
1

我做错了什么?

使用列表理解

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

输出应该是辅音的每个元素的索引

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

>>> [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

我在单词上使用了小写字母,因为在辅音列表中找不到大写字母"H"。

最新更新