为了账号安全,请及时绑定邮箱和手机立即绑定

返回具有给定元音数量的列表中的单词数

返回具有给定元音数量的列表中的单词数

慕无忌1623718 2021-11-09 16:21:48
有没有办法编辑这个程序,以便它返回列表中具有给定元音数量的单词数?我试过了,但似乎无法返回正确的数字,而且我不知道我的代码输出的是什么。(我是初学者)def getNumWordsWithNVowels(wordList, num):totwrd=0x=0ndx=0while ndx<len(wordList):    for i in wordList[ndx]:        if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U'):            x+=1        if x==num:            totwrd+=1        ndx+=1return totwrd打印(getNumWordsWithNVowels(aList,2))这输出“2”,但它应该输出“5”。
查看完整描述

1 回答

?
郎朗坤

TA贡献1921条经验 获得超9个赞

您可以将该sum函数与生成器表达式一起使用:


def getNumWordsWithNVowels(wordList, num):

    return sum(1 for w in wordList if sum(c in 'aeiou' for c in w.lower()) == num)

以便:


aList = ['hello', 'aloha', 'world', 'foo', 'bar']

print(getNumWordsWithNVowels(aList, 1))

print(getNumWordsWithNVowels(aList, 2))

print(getNumWordsWithNVowels(aList, 3))

输出:


2 # world, bar

2 # hello, foo

1 # aloha


查看完整回答
反对 回复 2021-11-09
  • 1 回答
  • 0 关注
  • 138 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信