gpt4 book ai didi

python - 在 reduce 函数中传递两个以上的参数

转载 作者:太空宇宙 更新时间:2023-11-03 12:47:58 24 4
gpt4 key购买 nike

我知道 Python reduce 只接受带有两个参数的函数。但是,有没有办法使函数可以使用两个以上的参数?我不想让它成为一个全局变量,因为它对所有其他导入都是可见的。以下片段可能有助于描述问题(请阅读片段中的评论):

# The reduce function
def apply_something(something, config):
# Consrtuct a class object based on the truth value of some other variable.
# some_var can be changed and is being accessed in different threads so its
# not safe to make it global. The reduce function is being called from
# inside some other function so It would be better to make
# some_var only accessible in the function context.

if some_var:
obj = Klass(some_var)
else:
obj = Klass()

def callee():
# This is how I apply the reduce operation.
reduce(apply_something, [1, 2, 3], something_initializer)

# I want something like this:
some_var = True # So this can be accessed in apply_something

请提供对此类问题的一些见解。

最佳答案

我想你要找的是 partial function application ,您可以使用 functools 来做到这一点.

def apply_something(something, config, some_var):
pass # ...

import functools

functools.reduce(functools.partial(apply_something, some_var=True),
[1, 2, 3], something_initializer)

例子:

>>> def foo(a, b, c):
... return a + b if c else a * b

>>> functools.reduce(functools.partial(foo, c=True), [1,2,3,4,5], 0)
15

>>> functools.reduce(functools.partial(foo, c=False), [1,2,3,4,5], 1)
120

关于python - 在 reduce 函数中传递两个以上的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25030548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com