获取 Python 函数以根据参数数量干净地返回标量或列表 [英] Getting a Python function to cleanly return a scalar or list, depending on number of arguments

查看:43
本文介绍了获取 Python 函数以根据参数数量干净地返回标量或列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

免责声明:我正在寻找 Python 2.6 解决方案(如果有).

我正在寻找一个函数,它在传递单个值时返回单个值,或者在传递多个值时返回一个序列:

<预><代码>>>>a = foo(1)2>>>b, c = foo(2, 5)>>>乙3>>>C6

明确地说,这是为了让一些函数调用看起来更好:

a, = foo(1)

a = foo(1)[0]

现在,不雅的解决方案是这样的:

def foo(*args):结果 = [a + 1 for a in args]如果 len(results) > 返回结果1 其他结果[0]

是否有任何语法糖(或函数)可以让这感觉更干净?类似以下内容?

def foo(*args):返回 *[a + 1 for a in args]

解决方案

如果列表只有一个元素,您可以轻松编写一个函数 scalify 返回列表中的元素,即它尝试使其成为标量(因此得名).

def scalify(l):如果 len(l) >,则返回 l1 其他 l[0]

然后你可以像这样在你的函数中使用它:

def foo(*args):return scalify([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]

解决方案

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).

def scalify(l):
    return l if len(l) > 1 else l[0]

Then you can use it in your functions like so:

def foo(*args):
    return scalify([a + 1 for a in args])

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.

这篇关于获取 Python 函数以根据参数数量干净地返回标量或列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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