解包函数参数 [英] unpacking function argument

查看:83
本文介绍了解包函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个函数需要n个参数,并且还有另一个函数返回一个包含n个项目的序列(或者我有一个包含n个项目的序列),有没有办法将这两个函数映射 (或者让第一个函数以n个项目的序列作为输入并返回结果)我不希望(也可能不能在某些情况下)自己编辑函数并更改其参数参数和返回值类型。



  def func1(x,y,z) :
return x + y + z

def func2(w):
return [i for i in range(w,w + 3)]

cant func1(func2(...))在这种情况下。

解决方案

您正在寻找 * args 参数语法:

 >>> def foo(bar,baz,spam):
...打印栏,baz,垃圾邮件
...
>>> arguments = [1,2,3]
>>> foo(* arguments)
1,2,3

传递参数给可调用对象时,任何以 * asterix开头的表达式都被解释为一系列位置参数,并被扩展为作为独立参数传递给被调用对象(函数,方法等)。 )。



举例来说:

  func1( * func2(...))

使用 * * double asterixes(需要映射),并且您也可以在函数签名中使用相同的语法。

请参阅关于调用表达式的文档,以及函数签名镜像语法关于函数定义的文档


if a function takes n number of arguments, and there is another function that returns a sequence with n number of items(or I have a sequence with n number of items), is there a way to 'map' these two functions(or make the first function take a sequence of n number of items as input and return result) I don't want (and maybe can't in some occasions) to edit the function myself and change its arguments parameters and return value types.

i.e)

def func1(x, y, z):
    return x+y+z

def func2(w):
    return [i for i in range(w,w+3)]

cant func1(func2( ... )) in this case.

解决方案

You are looking for the *args argument syntax:

>>> def foo(bar, baz, spam):
...     print bar, baz, spam
...
>>> arguments = [1, 2, 3]
>>> foo(*arguments)
1, 2, 3

When passing arguments to a callable, any expression preceded by a * asterix, is interpreted as a sequence of positional arguments, and expanded to be passed on as separate arguments to the called object (function, method, etc.).

For your example that would be:

func1(*func2(...))

There is a keyword equivalent using ** double asterixes (takes a mapping), and you can use the same syntax in function signatures too.

See the documentation on call expressions, and for the function signature mirror syntax, the documentation on function definitions.

这篇关于解包函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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