可以部分应用不带关键字参数的函数的第二个参数吗? [英] Can one partially apply the second argument of a function that takes no keyword arguments?

查看:19
本文介绍了可以部分应用不带关键字参数的函数的第二个参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以python内置的pow()函数为例.

Take for example the python built in pow() function.

xs = [1,2,3,4,5,6,7,8]

from functools import partial

list(map(partial(pow,2),xs))

>>> [2, 4, 8, 16, 32, 128, 256]

但是我如何将 xs 提高到 2 的幂?

but how would I raise the xs to the power of 2?

得到[1, 4, 9, 16, 25, 49, 64]

list(map(partial(pow,y=2),xs))

TypeError: pow() takes no keyword arguments

我知道列表理解会更容易.

I know list comprehensions would be easier.

推荐答案

根据文档partial 不能这样做(强调我自己的):

No

According to the documentation, partial cannot do this (emphasis my own):

partial.args

最左边 位置参数,将附加到位置参数

The leftmost positional arguments that will be prepended to the positional arguments


你总是可以修复"pow 有关键字参数:

_pow = pow
pow = lambda x, y: _pow(x, y)

这篇关于可以部分应用不带关键字参数的函数的第二个参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆