简体   繁体   English

从函数返回的解压缩可变长度列表

[英]Unpacking variable length list returned from function

Ok so I'm defining a function that takes a variable number of inputs and clamps each of them 好的,所以我定义了一个函数,该函数接受可变数量的输入并钳位每个输入

def clamp(*args):
    return [ max(min(arg, 0.8), 0.2) for arg in args]

I like the readability of this function: 我喜欢此函数的可读性:

a = 0.12
b = 0.45
c = 0.992

A,B,C = clamp(a,b,c)

print A,B,C

>> 0.2, 0.45, 0.8

This takes advantage of python's automatic unpacking of lists to tuples. 这利用了python自动将列表解包到元组的优势。 The trouble I am having is that if I only give one argument, python doesn't unpack it from the list and I get a list instead of a float, which is annoying. 我遇到的麻烦是,如果我只给出一个参数,python不会从列表中解压缩它,而是得到一个列表而不是浮点数,这很烦人。

print clamp(a)

>> [0.2]

My solution so far is to check the length of the list and index it if there is only one element: 到目前为止,我的解决方案是检查列表的长度并在只有一个元素的情况下对其进行索引:

def clamp(*args):
    result = [ max(0.2, min(0.8,arg)) for arg in args]
    return result if len(result) > 1 else result[0]

a = 0.12
print clamp(a)

>> [0.2]

My question is, is there a more idiomatic way to do this? 我的问题是,是否有更惯用的方式来做到这一点?

I'm not very conviced but here is an alternative solution 我不是很定罪,但这是替代解决方案

>>> clam = lambda a: max(min(a, 0.8), 0.2)

>>> def clamp(a, *args):
...     if args:
...        return [ clam(arg) for arg in (a,)+args]
...     else:
...        return clam(a)
... 
>>> clamp(123, 123)
[0.8, 0.8]
>>> clamp(123)
0.8

You can force it to unpack a single element by adding a comma after the name. 您可以通过在名称后添加逗号来强制其解压缩单个元素。 Not ideal but here you go: 不理想,但是您可以在这里:

A, = clamp(a)
def clamp(*args):
    rt = [max(min(arg, 0.8), 0.2) for arg in args]
    return rt if len(rt) > 1 else rt[0]

or else, remember how you make a tuple of one element. 否则,请记住如何使一个元素的元组。 Put a comma after A to force unpack for a single variable. A后面加上逗号,以强制解压缩单个变量。

A, = clamp(0.12) # with your old function which always returns list
def clamp(*args):
    lst = [max(min(arg, 0.8), 0.2) for arg in args]
    if len(lst)==1:
        return lst[0]
    return lst

I think when you call it with one element, you can add a , after the name. 我认为当你有一个元素调用它,您可以添加,名称后。 a, = clamp(1) . a, = clamp(1) In this case, you don't have to modify your function and the automatic unpacking still happens. 在这种情况下,您无需修改​​功能,仍然可以自动解压缩。

>>> a, b, c = [1,2,3]
>>> a
1
>>> b
2
>>> c
3
>>> a, = [1]
>>> a
1
>>> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM