The*_*Man 1 python for-loop python-2.7
程序word通过循环遍历字符串来识别字符串中的一个元素是辅音word,然后通过字符串对每次迭代进行迭代word,迭代consonants列表并比较word字符串中的当前元素是否等于consonant列表的当前元素.
如果是,则word字符串的当前元素是辅音并且辅音被打印(不是辅音的索引,而是实际的辅音,例如"d".)
问题是,我得到了这个:
1
1
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?嵌套循环不应该工作,以便下面的循环迭代上面循环中每个元素的每个元素吗?也就是说,上面的每个索引使得下面的循环遍历每个索引?
这是程序:
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
Run Code Online (Sandbox Code Playgroud)
你误读了输出.字符是字母L小写,而不是数字1.
换句话说,您的代码按设计工作.该下水管局信H是不是在你的consonants列表中,但两个小写字母l中Hello 的.
请注意,这将会是更有效的使用set为consonants这里; 你不必遍历整个列表,只是in用来测试成员资格.这也适用于列表,但使用集合效率更高.如果你小写这个word值,你也可以匹配H.
最后但并非最不重要的是,您可以直接循环word字符串而不是使用然后使用生成的索引:range(len(word))
word = "Hello"
consonants = set('bcdfghjklmnpqrstvwxz')
for character in word.lower():
if character in consonants:
print character
Run Code Online (Sandbox Code Playgroud)
演示:
>>> word = "Hello"
>>> consonants = set('bcdfghjklmnpqrstvwxz')
>>> for character in word.lower():
... if character in consonants:
... print character
...
h
l
l
Run Code Online (Sandbox Code Playgroud)