让 Python 函数根据参数数量干净地返回标量或列表
免责声明:我正在寻找一种 Python 2.6 解决方案(如果有的话)。
我正在寻找一个在传递单个值时返回单个值的函数,或者在传递多个值时返回一个序列的函数:
>>> a = foo(1)
2
>>> b, c = foo(2, 5)
>>> b
3
>>> c
6
要明确的是,这是为了使某些函数调用看起来比:
a, = foo(1)
或
a = foo(1)[0]
现在 更好,不优雅的解决方案是这样的:
def foo(*args):
results = [a + 1 for a in args]
return results if len(results) > 1 else results[0]
是否有任何语法糖(或函数)可以让这感觉更干净?像下面这样的东西吗?
def foo(*args):
return *[a + 1 for a in args]
Disclaimer: I'm looking for a Python 2.6 solution, if there is one.
I'm looking for a function that returns a single value when passed a single value, or that returns a sequence when passed multiple values:
>>> a = foo(1)
2
>>> b, c = foo(2, 5)
>>> b
3
>>> c
6
To be clear, this is in an effort to make some function calls simply look nicer than:
a, = foo(1)
or
a = foo(1)[0]
Right now, the inelegant solution is something along these lines:
def foo(*args):
results = [a + 1 for a in args]
return results if len(results) > 1 else results[0]
Is there any syntactic sugar (or functions) that would make this feel cleaner? anything like the following?
def foo(*args):
return *[a + 1 for a in args]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您始终可以编写一个装饰器来删除该 if 语句(如果这对您来说更好的话):
用法:
You can always write a decorator to elide that if statement if that is nicer to you:
Usage:
您可以轻松地编写一个函数
scalify
,如果列表只有一个元素,它会从列表中返回元素,即它会尝试使其成为标量(因此得名)。然后你可以在你的函数中使用它,如下所示:
这可以解决问题,但我同意那些建议你不要这样做的人。原因之一是,除非您知道至少传入了两项,否则它会排除对结果进行迭代。另外,如果您有一个列表,则在调用该函数时必须解压该列表,从而失去其“列表性”,并且您知道您可能无法取回列表。在我看来,这些缺点掩盖了您可能看到的该技术的任何好处。
You can easily write a function
scalify
that returns the element from the list if the list has only one element, i.e. it tries to make it a scalar (hence the name).Then you can use it in your functions like so:
This will do the trick, but I'm with those who suggest you don't do it. For one reason, it rules out iterating over the result unless you know you passed in at least two items. Also, if you have a list, you have to unpack the list when calling the function, losing its "listness," and you know you may not get a list back. These drawbacks seem to me to overshadow any benefit you may see to the technique.
您的意思是您想要一个具有相同数量参数的元组吗?这不是解决办法吗?
返回元组([a + 1 for a in args])
Do you mean you want a tuple with the same number of arguments? Is this not a solution?
return tuple([a + 1 for a in args])
:-) 这是地狱
:-) it is hell
这将处理 0 个或多个参数,我认为这就是您正在寻找的。
编辑:我修改为添加一个 None 列表,以防解压 0 参数
This will handle 0 or more args, I think that's what you're looking for.
edit: I revised to add a None list incase of unpacking 0 args