简体   繁体   English

如何将整数系列作为参数传递给python函数?

[英]How to pass an integer series as argument to a python function?

Is there a way to execute the following statement in a more concise way in python? 有没有办法在python中以更简洁的方式执行以下语句?

instead of 代替

a, b, c, d = f(1), f(2), f(3), f(4)

this: 这个:

a, b, c, d = some_way(f(x))

You can try map() : 你可以试试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

If your function arguments will always be consecutive, then you can also do: 如果你的函数参数总是连续的,那么你也可以这样做:

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

You can use list comprehension like this 你可以像这样使用列表理解

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

Or using map function, like this 或者使用map功能,就像这样

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

In both the cases, 在这两种情况下,

print a, b, c, d

will print 将打印

1 4 9 16

Edit: 编辑:

As mentioned in the comments section, here is the curried version 正如评论部分所述,这是curried版本

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

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

And then you can use the code shown above. 然后你可以使用上面显示的代码。 Instead of writing our own version of currying function, we can use functools.partial like this 我们可以像这样使用functools.partial ,而不是编写我们自己的currying函数版本

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

Just an additional comment that requires some code... in your case where you want to supply arguments, if you use a list comprehension, you don't need the curry function: 只是需要一些代码的附加注释...在您要提供参数的情况下,如果使用列表推导,则不需要curry函数:

# f(arg1, arg2, index)

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

List comprehensions are mostly equivalent in use to map, but this is one way in which they are superior. 列表推导在映射时大多等同于使用,但这是它们优越的一种方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM