【问题标题】:Returning the number of words in a list with a given number of vowels返回具有给定元音数量的列表中的单词数
【发布时间】:2019-02-14 23:45:04
【问题描述】:

有没有办法编辑这个程序,使其返回具有给定元音数量的列表中的单词数?

我试过了,但我似乎无法返回正确的数字,而且我不知道我的代码输出了什么。

(我是初学者)

def getNumWordsWithNVowels(wordList, num):
totwrd=0
x=0
ndx=0
while 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+=1
return totwrd

打印(getNumWordsWithNVowels(aList, 2))

这输出“2”但它应该输出“5”。

【问题讨论】:

  • 到目前为止你尝试过什么代码?错误是什么?
  • 不让我粘贴代码???
  • 你可以用 NLTK 包做到这一点:nltk.org
  • @TimothyWong 请使用edit 功能。通过在每行前面放置 4 个空格来格式化代码。
  • 编辑您的问题并将您的代码粘贴到其中。请记住选择您的代码并点击{} 按钮进行格式化。

标签: python function


【解决方案1】:

您可以将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

【讨论】:

  • 返回“sum”有什么作用?
  • sum 是一个内置函数,它返回给定序列中项目值的总和。详情请参考documentation
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多