小编The*_*Man的帖子

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

程序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)

python for-loop python-2.7

1
推荐指数
1
解决办法
46
查看次数

将新项目添加到列表中

如何将字符串附加到字符串列表中,尤其是列表中的特定字符串?

例如:

myList = ['apples', 'oranges', 'bananas']

newString = 'peach'
Run Code Online (Sandbox Code Playgroud)

我想将newString追加到myList的索引1('oranges')(以便newString出现在myList中的索引1之后.)我将如何去做?

python list append python-2.7

-3
推荐指数
1
解决办法
177
查看次数

标签 统计

python ×2

python-2.7 ×2

append ×1

for-loop ×1

list ×1