Unpacking variable length list returned from function

后端 未结 5 597
鱼传尺愫
鱼传尺愫 2021-01-25 18:44

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 a         


        
相关标签:
5条回答
  • 2021-01-25 19:13
    def clamp(*args):
        lst = [max(min(arg, 0.8), 0.2) for arg in args]
        if len(lst)==1:
            return lst[0]
        return lst
    
    0 讨论(0)
  • 2021-01-25 19:17

    I think when you call it with one element, you can add a , after the name. 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
    >>> 
    
    0 讨论(0)
  • 2021-01-25 19:19
    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, = clamp(0.12) # with your old function which always returns list
    
    0 讨论(0)
  • 2021-01-25 19:28

    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
    
    0 讨论(0)
  • 2021-01-25 19:29

    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)
    
    0 讨论(0)
提交回复
热议问题