问题:将元组扩展为参数

有没有一种方法可以将Python元组扩展为函数-作为实际参数?

例如,这里expand()做了魔术:

some_tuple = (1, "foo", "bar")

def myfun(number, str1, str2):
    return (number * 2, str1 + str2, str2 + str1)

myfun(expand(some_tuple)) # (2, "foobar", "barfoo")

我知道可以将其定义myfunmyfun((a, b, c)),但是当然可能会有遗留代码。谢谢

Is there a way to expand a Python tuple into a function – as actual parameters?

For example, here expand() does the magic:

some_tuple = (1, "foo", "bar")

def myfun(number, str1, str2):
    return (number * 2, str1 + str2, str2 + str1)

myfun(expand(some_tuple)) # (2, "foobar", "barfoo")

I know one could define myfun as myfun((a, b, c)), but of course there may be legacy code. Thanks


回答 0

myfun(*some_tuple)完全符合您的要求。的*操作者只需解包元组(或任何可迭代),并把它们作为位置函数的自变量。阅读有关解压缩参数的更多信息。

myfun(*some_tuple) does exactly what you request. The * operator simply unpacks the tuple (or any iterable) and passes them as the positional arguments to the function. Read more about unpacking arguments.


回答 1

请注意,您还可以扩展参数列表的一部分:

myfun(1, *("foo", "bar"))

Note that you can also expand part of argument list:

myfun(1, *("foo", "bar"))

回答 2

看一下Python教程的第4.7.3和4.7.4节。它讨论将元组作为参数传递。

我还将考虑使用命名参数(并传递字典),而不是使用元组并传递序列。当位置不直观或有多个参数时,我发现使用位置参数是一种不好的做法。

Take a look at the Python tutorial section 4.7.3 and 4.7.4. It talks about passing tuples as arguments.

I would also consider using named parameters (and passing a dictionary) instead of using a tuple and passing a sequence. I find the use of positional arguments to be a bad practice when the positions are not intuitive or there are multiple parameters.


回答 3

这是功能编程方法。它从语法糖中提升了元组扩展功能:

apply_tuple = lambda f, t: f(*t)

用法示例:

from toolz import * 
from operator import add, eq

apply_tuple = curry(apply_tuple)

thread_last(
    [(1,2), (3,4)],
    (map, apply_tuple(add)),
    list,
    (eq, [3, 7])
)
# Prints 'True'

咖喱的redefiniton apply_tuple节省了大量的partial,从长远来看通话。

This is the functional programming method. It lifts the tuple expansion feature out of syntax sugar:

apply_tuple = lambda f, t: f(*t)

Example usage:

from toolz import * 
from operator import add, eq

apply_tuple = curry(apply_tuple)

thread_last(
    [(1,2), (3,4)],
    (map, apply_tuple(add)),
    list,
    (eq, [3, 7])
)
# Prints 'True'

curry redefiniton of apply_tuple saves a lot of partial calls in the long run.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。