python - 比较和打印嵌套循环中的元素

标签 python python-2.7 for-loop

程序通过遍历 word 字符串来识别字符串 word 中的元素之一是否为辅音,然后每次迭代遍历 word 字符串,遍历 consonants 列表并比较 word 字符串中的当前元素是否等于 consonant 列表的当前元素。

如果是,则 word 字符串的当前元素是辅音并打印辅音(不是辅音的索引,而是实际的辅音,例如“d”。)

问题是,我得到的是:

1
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 character in range(len(word)): 
    for char in range(len(consonants)): 
        if consonants[char] == word[character]: 
            consonant = word[character]
            print consonant

最佳答案

误读了输出。该字符是小写的字母 L,而不是数字 1。

换句话说,您的代码按设计运行。大写字母 H 不在您的 consonants 列表中,而是 Hello 中的两个小写字母 l

请注意,在此处为辅音 使用set 会更有效;您不必遍历整个列表,只需使用 in 来测试成员资格。这也适用于列表,但使用集合更有效。如果您将 word 值小写,您也可以匹配 H

最后但同样重要的是,您可以直接遍历 word 字符串,而不是使用 range(len(word)) 然后使用生成索引:

word = "Hello"
consonants = set('bcdfghjklmnpqrstvwxz')

for character in word.lower():
    if character in consonants:
        print character

演示:

>>> word = "Hello"
>>> consonants = set('bcdfghjklmnpqrstvwxz')
>>> for character in word.lower():
...     if character in consonants:
...         print character
... 
h
l
l

关于python - 比较和打印嵌套循环中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28731960/

相关文章:

python - Curl 请求在 SSL 上失败

python - 在 Python 2.7 中计算和存储函数输出?

javascript - 对函数闭包感到困惑

python - 如何将 predict_generator 与 ImageDataGenerator 一起使用?

python - 如何在交叉验证和 GridSearchCV 中实现 SMOTE

python - 使用 Pandas 数据框中的值注释热图

python-2.7 - importError : no module named BaseHTTPServer 的问题

python - 从python中的字符串中获取两个字符

Java For 循环作为参数

python - Django 从 1.9 降级到 1.8