如何将整数序列作为参数传递给Python函数?

3
有没有更简洁的方法在Python中执行以下语句?而不是:
a, b, c, d = f(1), f(2), f(3), f(4)

this:

a, b, c, d = some_way(f(x))
3个回答

4
您可以尝试使用 map() 函数:
>>> def f(x): return x*x
... 
>>> a,b,c,d = map(f, (1,2,3,4))
>>> 
>>> a
1
>>> b
4
>>> c
9
>>> d
16

如果你的函数参数总是连续的,那么你也可以这样做:

>>> a,b,c,d = map(f, range(1,5))

@thefourtheye,我假设OP的值不总是连续的,但如果是,则是的。 - arshajii
如果原本的语句是 a,b,c,d = f(some_arg, other_arg, 1), f(some_arg, other_arg, 2), f(some_arg, other_arg, 3), f(some_arg, other_arg, 1),那么如何使用 map - alwbtc
@alwbtc 对于所有情况,some_argother_arg是否都相同? - thefourtheye

3

您可以像这样使用列表推导式

a, b, c, d = [f(i) for i in xrange(1, 5)]

或者使用 map 函数,像这样
a, b, c, d = map(f, xrange(1, 5))

在这两种情况下,
print a, b, c, d

将打印

1 4 9 16

编辑:

正如评论部分所提到的,这里是柯里化(curried)版本。

def curry_function(function, first, second):
    return lambda third: function(first, second, third)

f = curry_function(f, "dummy1", "dummy2")

然后你可以使用上面展示的代码。我们可以像这样使用functools.partial,而不是编写我们自己的柯里化函数。

from functools import partial
f = partial(f, "dummy1", "dummy2")

partial 方法中是否存在某种循环引用? - alwbtc
@alwbtc 不是的,它只是用新函数替换旧函数,并记住旧函数并通过“map”函数传递dummy1dummy2和新参数,以及记住的旧函数。很酷,对吧? :) - thefourtheye
没错,很酷。更酷的是,SO上的人们知道很多东西。 - alwbtc
@alwbtc 我也是从 Stack Overflow 学到的。现在我也想回馈社区 :) - thefourtheye

0
只是一个需要一些代码的补充注释...在您想要提供参数的情况下,如果您使用列表推导式,则不需要curry函数:
# f(arg1, arg2, index)

a,b,c,d = [f(arg1, arg2, x) for x in range(1,5)]

列表推导式在使用上大多等同于map函数,但这是它们卓越的一种方式。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接