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

时间:2015-02-19 19:22:34

标签: python python-2.7 for-loop

我在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

我做错了什么?

3 个答案:

答案 0 :(得分:2)

使用列表理解

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

答案 1 :(得分:1)

  

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

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

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

答案 2 :(得分:1)

这段代码怎么样

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'。