是否可以为方法编写包装函数?
>>> lowtide = [ 'oh', 'i', 'do', 'like', 'to', 'be', 'beside', 'the', 'seaside' ]
>>> [ x.capitalize() for x in lowtide ]
['Oh', 'I', 'Do', 'Like', 'To', 'Be', 'Beside', 'The', 'Seaside']
>>> list(map(lambda x: x.capitalize(), lowtide))
['Oh', 'I', 'Do', 'Like', 'To', 'Be', 'Beside', 'The', 'Seaside']
>>> def mef(m):
... def _mef(m,x):
... return x.m()
... return partial(_mef, m)
...
>>> list(map(mef(capitalize), lowtide))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'capitalize' is not defined
最佳答案
你可以简单地做
list(map(str.capitalize, lowtide))
在 Python 3.x 中,str.capitalize()
是一个接受单个参数 self
的函数。
在 Python 2.x 中,str.capitalize()
是一个“未绑定(bind)方法”,但其行为类似于采用单个参数的函数。
关于python - 是否可以将字符串方法视为函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11570426/