简体   繁体   中英

Use enumerate to find indices of all words with letter 'x'

How use enumerate to help find the indices of all words containing 'x'

Thank you

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)

Your code is almost complete:

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

This checks, for every single word, if there is an x in it. If so, it adds the index to indices .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM