Python 3.5 "for loop" "enumerate()" Select 列表中的单词

Python 3.5 "for loop" "enumerate()” Select Word from List

嗨,我是新来的,我刚开始学习python

wordList中的单个单词将被称为“单词”作为变量。

顺便说一句,我会为 python 英语语法生成程序设置这个。

我还想尝试输入一个循环,为 wordList 中的每个单词重复一次。尝试使用带有“enumerate()”函数的 for 循环,但我总是卡住。任何帮助都会很棒。

print('Welcome to my English Test App')



# Import the random module to allow us to select the word list and questions at random.
import random
candidateWords = ['HELLO', 'GOODBYE', 'NAME', 'DAY', 'NIGHT', 'HOUR', 'POTATO', 'BIG', 'SMALL', 'GOOD', 'BAD', 'YES', 'NO', 'HOUSE', 'QUESTION', 'BALLOON', 'CAT', 'DUCK', 'PIGEON', 'POSTER', 'TELEVISION', 'SPY', 'RHYTHM', 'SUBSTANTIAL', 'SNOW', 'MAGNET', 'TOWEL', 'WALKING', 'SPEAKER', 'UNCHARACTERISTICALLY']
# places words down in a list
s = random.sample (candidateWords, 5)
for index,w in enumerate(s):
print(index,w)

如果您的问题是如何使用枚举,这里有一个适用于您的代码示例的应用程序:

import random
candidateWords = ['HELLO', 'GOODBYE', 'NAME', 'DAY', 'NIGHT', 'HOUR', 'POTATO', 'BIG', 'SMALL', 'GOOD', 'BAD', 'YES', 'NO', 'HOUSE', 'QUESTION', 'BALLOON', 'CAT', 'DUCK', 'PIGEON', 'POSTER', 'TELEVISION', 'SPY', 'RHYTHM', 'SUBSTANTIAL', 'SNOW', 'MAGNET', 'TOWEL', 'WALKING', 'SPEAKER', 'UNCHARACTERISTICALLY']

s = random.sample (candidateWords, 5)

# loop through the list using enumerate

for index,w in enumerate(s):
    print("word {} out of {} is {}, nb vowels is {}".format(index+1,len(s),w,countVowels(w)))

产出

word 1 out of 5 is NIGHT, nb vowels is 1
word 2 out of 5 is BALLOON, nb vowels is 3
word 3 out of 5 is SUBSTANTIAL, nb vowels is 4
word 4 out of 5 is BIG, nb vowels is 1
word 5 out of 5 is PIGEON, nb vowels is 3

请注意,如果不需要索引,则不必使用枚举:

for w in s:
    print(w,countVowels(w))

对于你的计数元音(因为每个人似乎都认为这是某个时候的问题),你可以这样做,Y 是否是元音取决于你,因为它不清楚(Oxford )

def countVowels(word):
    return sum(word.count(x) for x in "AEIOUY")

生成器 comp 将为单词中的每个元音应用计数字符,然后应用标准求和函数。

print('Welcome to my English Test App')

#Import the random module to allow us to select the word list and questions at random.

import random

candidateWords = ['HELLO', 'GOODBYE', 'NAME', 'DAY', 'NIGHT', 'HOUR', 'POTATO', 'BIG', 'SMALL', 'GOOD', 'BAD', 'YES', 'NO', 'HOUSE', 'QUESTION', 'BALLOON', 'CAT', 'DUCK', 'PIGEON', 'POSTER', 'TELEVISION', 'SPY', 'RHYTHM', 'SUBSTANTIAL', 'SNOW', 'MAGNET', 'TOWEL', 'WALKING', 'SPEAKER', 'UNCHARACTERISTICALLY']

# places words down in a list
s = random.sample (candidateWords, 5)
for index,w in enumerate(s):
    print(index,w)   #your code have indent problem