相关疑难解决方法(0)

Python:为什么functools.partial是必要的?

部分应用很酷.什么功能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 functional-programming partial-application

183
推荐指数
6
解决办法
4万
查看次数

Python函数作为函数参数?

Python函数可以作为另一个函数的参数吗?

说:

def myfunc(anotherfunc, extraArgs):
    # run anotherfunc and also pass the values from extraArgs to it
    pass
Run Code Online (Sandbox Code Playgroud)

所以这基本上是两个问题:

  1. 它是否允许?
  2. 如果是,如何在其他功能中使用该功能?我需要使用exec(),eval()或类似的东西吗?永远不需要弄乱它们.

BTW,extraArgs是anotherfunc参数的列表/元组.

python arguments function

103
推荐指数
4
解决办法
18万
查看次数

Python参数绑定器

如何将参数绑定到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)

python partial-application

60
推荐指数
5
解决办法
2万
查看次数

Python参数作为字典

如何将参数名称及其值作为字典传递给方法?

我想为GET请求指定可选和必需的参数作为HTTP API的一部分,以便构建URL.我不确定制作这种pythonic的最佳方法.

python dictionary arguments

43
推荐指数
2
解决办法
7万
查看次数

Python:传递一个带参数的函数作为参数

def lite(a,b,c):
    #...

def big(func): # func = callable()
    #...


#main
big(lite(1,2,3))
Run Code Online (Sandbox Code Playgroud)

这该怎么做?
以什么方式将带参数的函数传递给另一个函数?

python function

23
推荐指数
3
解决办法
2万
查看次数

是否有Python方式将可选功能与功能的主要用途脱钩?

语境

假设我有以下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

11
推荐指数
1
解决办法
280
查看次数

在python中将公式作为函数参数传递

我想在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中有什么可能吗?还是其他任何想法?谢谢

python function

4
推荐指数
1
解决办法
6223
查看次数

Ruby中的基准测试方法

我试图像这样对一组计算进行基准测试 -

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中的另一个函数? 有人可以帮忙吗?谢谢.

ruby benchmarking

3
推荐指数
1
解决办法
3414
查看次数

如何将函数或运算符作为参数传递给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可能是用户输入的代码显然是危险的.

python math function

2
推荐指数
1
解决办法
1789
查看次数

将计算方法传递给函数的最简单方法

我想将不同的计算方法传递给函数,例如:

def example_func(method='mean'):
    result = np.+method([1,2,3,4])
Run Code Online (Sandbox Code Playgroud)

什么是最简单,最富有成效的方法(除了字典......)

python function

2
推荐指数
1
解决办法
78
查看次数

Python按具有多个参数的函数对列表进行排序

我想使用返回浮点值的函数对列表进行排序。如果函数只有一个参数,我会简单地使用

sorted(mylist, key=myfunction)
Run Code Online (Sandbox Code Playgroud)

并在我快乐的方式。但是,这不适用于具有多个参数的函数。如何才能做到这一点?

编辑:

人们询问更多细节,所以我们开始:

这是国际象棋引擎的一小部分。'Bestmove' 函数接受棋盘位置(一个列表)、深度(一个整数)和 alpha/beta 值,并返回一个包含两个条目的列表:棋盘评估(一个浮点数)和建议的移动(一个列表)。

为了优化 alpha/beta 修剪过程,我想更改评估移动的顺序(首先评估的强移动会导致更高的效率)。为此,我想按“Bestmove”函数返回的列表中的第一个值对移动列表进行排序。

python sorting list

1
推荐指数
1
解决办法
3678
查看次数

如何执行函数列表并将数据传递给使用 asyncio 调用的适当函数

我以前使用的是 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)

python asynchronous python-asyncio

1
推荐指数
1
解决办法
2766
查看次数

如何将函数名称和参数的可变参数列表传递给 C++ 中的函数?

不是What is std::invoke in c++?的重复项 。该问题专门询问了这一唯一的功能。这个问题询问一个概念,无需该功能即可 100% 解决,并且有多种替代解决方案,其中只有一些甚至使用该功能。


在 Python 中,您可以将函数名称和参数列表传递给外部函数,该外部函数调用内部函数并将这些参数传递给它,如下所示:

在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++ 中做到这一点?

c++ variadic variadic-templates parameter-pack

0
推荐指数
1
解决办法
1070
查看次数