函数中的未命名参数:等效于R的三点

时间:2019-04-02 21:46:34

标签: python

来自R,我想知道Python中是否有R的{​​{1}}的等效物?

...中,三点在函数中非常有用,因为它允许传递任何类型的参数(命名,未命名,任何类型,任何类等)。例如

R

Python中有类似的东西吗?

我想具有类似的功能

fun <- function (...) return(list(...))
fun(a=1, b=2, weather=c("sunny", "warm"))
# returns
# $a
# [1] 1

# $b
# [1] 2

# $weather
# [1] "sunny" "warm"

1 个答案:

答案 0 :(得分:3)

这是接收任意数量参数的方法:

def function(*arguments):
    print("received {} arguments".format(len(arguments)))

然后您可以将其命名为这样:

>>> function(5,5,6)
received 3 arguments

arguments变量是一个包含所有参数的元组。

另一方面,如果要命名参数,则可以执行以下操作:

def function(**keyword_arguments):
    print("received {} arguments".format(len(keyword_arguments)))

然后您可以将其命名为这样:

>>> function(a=4, b=7)
received 2 arguments

keyword_arguments变量包含传递的参数的字典。

另请参阅Python Documentation on Keyword Arguments