【发布时间】: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 是的,我知道,但我有我的班级必须遵循的标准。这也解决了我的问题,谢谢!