可以在 lambda 函数中增加像
int
这样的数字对象吗?
想象一下有一个窥视功能,例如:
def _peek(cb, iter):
for i in iter:
cb(i)
如何查看这些值并将其添加到总和中,如以下简单示例所示:
numbers = (1, 2, 3)
s = 0
# Doesn't work, because __add__ doesn't add inline
_peek(s.__add__, numbers)
# Doesn't work, because s is outside of scope (syntax error)
_peek(lambda x: s += x, numbers)
# Does work, but requires an additional function
def _sum(var):
nonlocal s
s += var
_peek(_sum, numbers)
# Does work, but reduces numbers
sum = reduce(lambda x, y: x+y, numbers)
这是一个现实世界的例子:
@dataclass
class Vote:
count = 0
def add_count(self, count: int):
self.count += count
vote = Vote()
# Doesn't work work
_peek(lambda x: vote.count += x, map(lambda x: x['count'], data))
# Does work, but requires additional function
_peek(vote.add_count, map(lambda x: x['count'], data))
在Java中,我可以轻松编写:
@Test
public void test_numbers() {
class Vote {
int count = 0;
}
var vote = new Vote();
var count = Stream.of(1,2,3).peek(i -> vote.count+=i).filter(i -> i > 1).count();
assert vote.count == 6;
assert count == 2;
}
您可以使用可调用类。
def _peek(cb, iter):
for i in iter:
cb(i)
class Adder:
def __init__(self, *args, **kwargs):
self.value = 0
def __call__(self, *args, **kwargs):
self.value += args[0]
adder = Adder()
_peek(adder, (1, 2, 3))
print(adder.value)
结果是
6
。
如果我们将总和放入容器(例如列表)中,那么我们可以引用该容器而不必担心范围;我们可以使用
.append
和 .pop
: 等方法来改变它的内容(即总和)
def _peek(cb, iter):
for i in iter:
cb(i)
numbers = (1, 2, 3)
s_container = [0]
_peek(lambda x: s_container.append(s_container.pop() + x), numbers)
# Extract the result
s = s_container.pop()