使用enumerate查找字母'x'的所有单词的索引

时间:2016-09-15 00:28:03

标签: python python-3.x

如何使用枚举来帮助查找包含'x'

的所有单词的索引

谢谢

wordsFile = open("words.txt", 'r')
words = wordsFile.read()
wordsFile.close()
wordList = words.split()

indices=[]

for (index, value) in enumerate(wordList):
    if value == 'x':

print("These locations contain words containing the letter 'x':\n",indices)

1 个答案:

答案 0 :(得分:1)

您的代码已基本完成:

for (index, value) in enumerate(wordList):
    if 'x' in value:
        indices.append(index)

如果每个单词中都有x,则会检查每个单词。如果是,则将索引添加到indices