Python 从列表打印复数
很好,但我正在尝试编写一个函数,它可以打印单词列表中的所有复数单词 因此,产出将是:Python 从列表打印复数,python,list,loops,for-loop,plural,Python,List,Loops,For Loop,Plural,很好,但我正在尝试编写一个函数,它可以打印单词列表中的所有复数单词 因此,产出将是: >>> printPlurals(['computer', 'computers', 'science,', 'sciences']) computers sciences 这就是我到目前为止所拥有的,但我没有得到任何输出。任何帮助都会很好。泰 def printPlurals(list1): plural = 's' for letter in list1:
>>> printPlurals(['computer', 'computers', 'science,', 'sciences'])
computers
sciences
这就是我到目前为止所拥有的,但我没有得到任何输出。任何帮助都会很好。泰
def printPlurals(list1):
plural = 's'
for letter in list1:
if letter[:-1] == 's':
return list1
一种简单的方法是
def printPlurals(list1):
print [word for word in list1 if word[-1]=='s']
您的主要问题是字母[:-1]
将返回所有到最后一个字母的内容。对于最后一个字母,请使用[-1]
。您还返回了值,而没有打印。您可以只解决这两个问题,也可以在这个答案中使用一行
所以你的代码是:
def printPlurals(list1):
plural = 's' #you don't need this line, as you hard coded 's' below
for letter in list1:
if letter[-1] == 's':
print list1
你真的很接近,但你把一些事情弄混了。首先,您不需要使用
复数变量。反正你也不用。其次,从命名的角度来看,将变量命名为letter
并不重要,但这意味着你可能认为你在循环字母。由于您实际上是在列表list1
的成员之间循环,因此每次迭代都要考虑一个单词。最后,您不想返回列表。相反,我认为您希望打印已确认以s
结尾的单词。尝试以下方法。祝你好运
def print_plurals(word_list):
for word in word_list:
if word[-1] == 's':
print word
如果您有兴趣做一些更有趣的事情(或者可以说是“Pythonic”),您可以通过列表理解形成复数列表,如下所示:
my_list = ['computer', 'computers', 'science', 'sciences']
plural_list = [word for word in my_list if word[-1]=='s']
您考虑过使用Python库吗
<> p>奇数个名词<代码>,因为你问了多个值,看起来很奇怪,但是当你认为<>代码> P.SuxLoopyNub(Word)< /> >返回<代码> false <代码> > <代码> Word < /C>已经是单数时,它是有意义的。因此,您可以使用它来过滤非单数的单词。打印(字母)
而不是返回列表1
没有打印出任何内容@inspectorG4dgetI忘了提到您还应该将如果字母[:-1]
更改为如果字母[-1]
(注意缺少的:
)非常感谢!我很难挑出每一封信,但实际上我没有。我刚刚开始学习python,还没有进入高级阶段,但是很高兴知道我不熟悉的不同方法,比如那个!非常感谢。
p = inflect.engine()
words = ['computer', 'computers', 'science', 'sciences']
plurals = (word for word in words if p.singular_noun(word))
print "\n".join(plurals)