【问题标题】:Function that which takes a list of strings and capitalizes them appropriately as a book or movie title (Check body for more info)函数获取字符串列表并将它们适当地大写为书籍或电影标题(查看正文以获取更多信息)
【发布时间】:2021-07-11 04:10:44
【问题描述】:

具体来说,第一个单词一定要大写,长度至少为4的单词也要大写,其他单词要小写。例如,title(['tHe', 'souND', 'AND', 'the', 'fUrY']) 返回['The', 'Sound', 'and', 'the', 'Fury']. 您可以假设列表中的每个字符串仅包含表示英文字母的字符。我必须使用当前调用其他辅助函数的方法来执行此功能。并且只能使用map、reduce、list、filter、lambda。

目前我的代码是:

def title(l):
    return [capitalize(l[0])] + (list(map(lambda x: capitalize if len(x) >= 4 else allLower, l[1:])))
print(title(['tHe', 'souND', 'AND', 'the', 'fUrY']))

我在这个函数中调用的函数我称为我的辅助函数,它们由更多的辅​​助函数组成。参考以下代码:

def toUpper(c):
    o = ord(c)
    if o >= 97:
        return chr(o - 32)
    else:
        return c  #: Finished


def toLower(c):
    o = ord(c)
    if o <= 90:
        return chr(o + 32)
    else:
        return c  #: Finished


def allLower(s):
    return reduce(lambda x, y: x + y, map(toLower, s))

print(allLower('HELLO'))


def capitalize(s):
   return toUpper(s[0]) + reduce(lambda x, y: x + y, map(toLower, s[1:]))
print(capitalize("hello"))

目前我的标题函数正在返回,它应该返回示例显示的内容(请参阅此问题的开头文本):

['The', <function capitalize at 0x000002460A48EB80>, <function allLower at 0x000002460A48E700>, <function allLower at 0x000002460A48E700>, <function capitalize at 0x000002460A48EB80>]

【问题讨论】:

  • 您需要lamba x: capitalize(x),而不是lambda x: capitalize。与“允许”相同。 lambda 应该返回一个值,而不是一个函数。顺便说一句,您是否知道 Python 字符串已经提供了您在此处编写的所有三个函数?
  • @TimRoberts 是的,我知道,但我有我的班级必须遵循的标准。这也解决了我的问题,谢谢!

标签: python list function


【解决方案1】:

你可以做一些简单的事情,比如:

def wordCasing(word):
    return word.capitalize() if len(word)>3 else word.lower()

title = ['tHe', 'souND', 'AND', 'the', 'fUrY']
result = list(map(wordCasing, title))
result[0] =result[0].capitalize()
print (result)

【讨论】:

  • 谢谢你,我会尝试做一些更简单的事情,但我必须遵循某些标准。但为了将来参考,我会注意这一点。
猜你喜欢
  • 2013-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-17
  • 2014-09-13
相关资源
最近更新 更多