Assign contents of Python dict to multiple variables at once?

前端 未结 5 2297
滥情空心
滥情空心 2021-02-20 07:41

I would like to do something like this

def f():
    return { \'a\' : 1, \'b\' : 2, \'c\' : 3 }

{ a, b } = f()     # or { \'a\', \'b\' } = f() ?
<
5条回答
  •  天涯浪人
    2021-02-20 08:21

    You could use (or abuse) a function attribute to do this:

    >>> def f():
    ...    f.a=1
    ...    f.b=2
    ...    return { 'a' : f.a, 'b' : f.b, 'c' : 3 }
    ... 
    >>> f()
    {'a': 1, 'c': 3, 'b': 2}
    >>> a,b=f.a,f.b
    >>> a,b
    (1, 2)
    

    Be aware that the attributes only have value after f() is called or manually assigned.

    I (rarely) use function attributes as a fill-in for C's static class variables like so:

    >>> def f(i):
    ...    f.static+=i
    ...    return f.static
    >>> f.static=0
    >>> f(1)
    1
    >>> f(3)
    4
    

    There are better ways to do this, but just to be complete...

提交回复
热议问题