【问题标题】:Printing plurals from a list从列表中打印复数
【发布时间】:2014-10-24 02:30:37
【问题描述】:

漂亮的菜鸟,但我正在尝试编写一个函数来打印单词列表中的所有复数单词

所以输出将是:

 >>> printPlurals(['computer', 'computers', 'science,', 'sciences'])
 computers
 sciences

这是我目前所拥有的,但我没有得到任何输出。任何帮助都会很棒。太棒了。

def printPlurals(list1):
    plural = 's'

    for letter in list1:
        if letter[:-1] == 's':
            return list1

【问题讨论】:

  • print(letter) 而不是 return list1
  • 没有任何东西打印出来@inspectorG4dget
  • 我忘了说你也应该把if letter[:-1]改成if letter[-1](注意缺少:

标签: python list loops for-loop plural


【解决方案1】:

你真的很接近,但你把一些事情搞混了。对于初学者,您不需要有 plural 变量。反正你没用。其次,从命名的角度来看,您将变量命名为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']

【讨论】:

  • 非常感谢!我很难找出每个字母
【解决方案2】:

您是否考虑过使用 Python inflect 库?

p = inflect.engine()
words = ['computer', 'computers', 'science', 'sciences']
plurals = (word for word in words if p.singular_noun(word))
print "\n".join(plurals)

检查if p.singular_noun 可能看起来很奇怪,因为您要求的是复数值,但是当您考虑到p.singular_noun(word)word 已经是单数时返回False 时,这很有意义。所以你可以用它来过滤单数的词。

【讨论】:

  • 其实我没有。我刚开始学习python,还没有进入高级阶段,但是很高兴知道我不熟悉的不同方法,比如那个!谢谢!
【解决方案3】:

做到这一点的一种方法是

def printPlurals(list1):
    print [word for word in list1 if word[-1]=='s']

您的主要问题是letter[:-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

【讨论】:

    猜你喜欢
    • 2022-08-08
    • 1970-01-01
    • 2017-04-12
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多