部分应用很酷.什么功能functools.partial提供你无法通过lambdas?
>>> sum = lambda x, y : x + y
>>> sum(1, 2)
3
>>> incr = lambda y : sum(1, y)
>>> incr(2)
3
>>> def sum2(x, y):
return x + y
>>> incr2 = functools.partial(sum2, 1)
>>> incr2(4)
5
Run Code Online (Sandbox Code Playgroud)
在functools某种程度上更有效,或可读?
Python函数可以作为另一个函数的参数吗?
说:
def myfunc(anotherfunc, extraArgs):
# run anotherfunc and also pass the values from extraArgs to it
pass
Run Code Online (Sandbox Code Playgroud)
所以这基本上是两个问题:
BTW,extraArgs是anotherfunc参数的列表/元组.
如何将参数绑定到Python方法以存储一个用于以后调用的nullary仿函数?与C++类似boost::bind.
例如:
def add(x, y):
return x + y
add_5 = magic_function(add, 5)
assert add_5(3) == 8
Run Code Online (Sandbox Code Playgroud) 如何将参数名称及其值作为字典传递给方法?
我想为GET请求指定可选和必需的参数作为HTTP API的一部分,以便构建URL.我不确定制作这种pythonic的最佳方法.
def lite(a,b,c):
#...
def big(func): # func = callable()
#...
#main
big(lite(1,2,3))
Run Code Online (Sandbox Code Playgroud)
这该怎么做?
以什么方式将带参数的函数传递给另一个函数?
假设我有以下Python代码:
def example_function(numbers, n_iters):
sum_all = 0
for number in numbers:
for _ in range(n_iters):
number = halve(number)
sum_all += number
return sum_all
ns = [1, 3, 12]
print(example_function(ns, 3))
Run Code Online (Sandbox Code Playgroud)
example_function这里只是遍历ns列表中的每个元素,并将它们减半3次,同时累积结果。运行此脚本的输出很简单:
2.0
Run Code Online (Sandbox Code Playgroud)
由于1 /(2 ^ 3)*(1 + 3 + 12)= 2。
现在,让我们说(出于任何原因,也许是调试或日志记录),我想显示一些有关所采取的中间步骤的信息example_function。也许然后我会将此函数重写为如下所示:
def example_function(numbers, n_iters):
sum_all = 0
for number in numbers:
print('Processing number', number)
for i_iter in range(n_iters):
number = number/2
print(number)
sum_all += number
print('sum_all:', sum_all)
return sum_all
Run Code Online (Sandbox Code Playgroud)
现在,当使用与以前相同的参数调用它时,将输出以下内容:
Processing number 1 …Run Code Online (Sandbox Code Playgroud) 我想在Python中的函数参数中传递一个公式,其中公式是其他函数参数的组合.原则上,这将是这样的:
myfunction(x=2,y=2,z=1,formula="x+2*y/z")
6
Run Code Online (Sandbox Code Playgroud)
或更具体:
def myformula(x,y,z,formula):
return formula(x,y,z)
Run Code Online (Sandbox Code Playgroud)
这将允许用户根据x,y和z选择任何算术表达式,而无需创建新函数.
我预见的一种可能性是在函数内的代码行中转换字符串.在Python中有什么可能吗?还是其他任何想法?谢谢
我试图像这样对一组计算进行基准测试 -
def benchmark(func, index, array)
start = Time.now
func(index, array)
start - Time.now #returns time taken to perform func
end
def func1(index, array)
#perform computations based on index and array
end
def func2(index, array)
#more computations....
end
benchmark(func1, index1, array1)
benchmark(func1, index2, array2)
Run Code Online (Sandbox Code Playgroud)
现在我想知道如何实现这一目标.我试过这个例子,但是吐了出来
`func1': wrong number of arguments (0 for 2) (ArgumentError)
Run Code Online (Sandbox Code Playgroud)
如果我尝试 -
benchmark(func1(index1, array1), index1, array1)
Run Code Online (Sandbox Code Playgroud)
吐出来......
undefined method `func' for main:Object (NoMethodError)
Run Code Online (Sandbox Code Playgroud)
我看到了一个类似的问题,但它是为了python.使用参数将函数传递给Python中的另一个函数? 有人可以帮忙吗?谢谢.
...同时仍然在函数中保持可执行文件.
这背后的想法是我想创建一个求和函数.这是我到目前为止所拥有的:
def summation(n, bound, operation):
if operation is None and upper != 'inf':
g = 0
for num in range(n, limit + 1):
g += num
return g
else:
pass
Run Code Online (Sandbox Code Playgroud)
但总结通常是关于无限收敛系列(我使用它'inf'),操作应用于每个术语.理想情况下,我希望能够编写print summation(0, 'inf', 1 / factorial(n))并获得数学常数e,或者def W(x): return summation(1, 'inf', ((-n) ** (n - 1)) / factorial(n))获得Lambert W函数.
我想到的只是将相应的算法作为字符串传递,然后使用该exec语句来执行它.但我不认为这会完成整个事情,并且使用exec可能是用户输入的代码显然是危险的.
我想将不同的计算方法传递给函数,例如:
def example_func(method='mean'):
result = np.+method([1,2,3,4])
Run Code Online (Sandbox Code Playgroud)
什么是最简单,最富有成效的方法(除了字典......)
我想使用返回浮点值的函数对列表进行排序。如果函数只有一个参数,我会简单地使用
sorted(mylist, key=myfunction)
Run Code Online (Sandbox Code Playgroud)
并在我快乐的方式。但是,这不适用于具有多个参数的函数。如何才能做到这一点?
编辑:
人们询问更多细节,所以我们开始:
这是国际象棋引擎的一小部分。'Bestmove' 函数接受棋盘位置(一个列表)、深度(一个整数)和 alpha/beta 值,并返回一个包含两个条目的列表:棋盘评估(一个浮点数)和建议的移动(一个列表)。
为了优化 alpha/beta 修剪过程,我想更改评估移动的顺序(首先评估的强移动会导致更高的效率)。为此,我想按“Bestmove”函数返回的列表中的第一个值对移动列表进行排序。
我以前使用的是 requests,但后来我转向 aiohttp + asyncio 来并行运行帐户,但是我在将逻辑放在脑海中时遇到了困难。
class Faked(object):
def __init__(self):
self.database = sqlite3.connect('credentials.db')
async def query_login(self, email):
print(email)
cur = self.database.cursor()
sql_q = """SELECT * from user WHERE email='{0}'""".format(email)
users = cur.execute(sql_q)
row = users.fetchone()
if row is None:
raise errors.ToineyError('No user was found with email: ' + email + ' in database!')
self.logger().debug("Logging into account '{0}'!".format(row[0]))
call_func = await self._api.login(data={'email': row[0],
'password': row[1],
'deviceId': row[2],
'aaid': row[3]})
return await call_func
async def send_friend_request(self, uid):
return await self._api.send_friend_request(uid)
def main(funcs, …Run Code Online (Sandbox Code Playgroud) 不是What is std::invoke in c++?的重复项 。该问题专门询问了这一唯一的功能。这个问题询问一个概念,无需该功能即可 100% 解决,并且有多种替代解决方案,其中只有一些甚至使用该功能。
在 Python 中,您可以将函数名称和参数列表传递给外部函数,该外部函数调用内部函数并将这些参数传递给它,如下所示:
def perform(fun, *args):
fun(*args)
def action1(args):
# something
def action2(args):
# something
perform(action1)
perform(action2, p)
perform(action3, p, r)
Run Code Online (Sandbox Code Playgroud)
我如何在 C++ 中做到这一点?
python ×11
function ×5
arguments ×2
asynchronous ×1
benchmarking ×1
c++ ×1
dictionary ×1
list ×1
math ×1
ruby ×1
sorting ×1
variadic ×1