擅长:python、mysql、java
<p>看起来是<a href="https://docs.python.org/3/library/functools.html#functools.singledispatch" rel="nofollow noreferrer">^{<cd1>} decorator</a>的完美任务:</p>
<pre><code>from functools import singledispatch
@singledispatch
def apply(xs, f):
return map(f, xs)
@apply.register(list)
def apply_to_list(xs, f):
return type(xs)(map(f, xs))
@apply.register(tuple)
def apply_to_tuple(xs, f):
try:
# handle `namedtuple` case
constructor = xs._make
except AttributeError:
constructor = type(xs)
return constructor(map(f, xs))
</code></pre>
<p>之后<code>apply</code>函数可以简单地使用如下</p>
<pre><code>>>> apply([1, 2], lambda x: x + 1)
[2, 3]
>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(10, 5)
>>> apply(p, lambda x: x ** 2)
Point(x=100, y=25)
</code></pre>
<p>虽然我不知道<code>dict</code>对象需要什么样的行为,但是这种方法的伟大之处在于它很容易扩展。你知道吗</p>