Python 3.5“for loop”“enumerate()”从列表中选择Word

时间:2016-08-27 06:45:53

标签: python python-3.x for-loop enumerate

你好,我刚开始学习python

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

顺便说一下,我会为python英语语法gen程序设置这个。

我也想尝试输入一个循环,对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)

2 个答案:

答案 0 :(得分:0)

如果你的问题是如何使用枚举,这里是你的代码示例的应用程序:

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是否是元音取决于你,因为它不清楚({{3 }})

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

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

答案 1 :(得分:0)

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