Assign Many Variables at Once, Python

后端 未结 2 897
慢半拍i
慢半拍i 2021-01-23 08:59

Is there a better way to do this?

a, b, c, = \"yyy\", \"yyy\", \"yyy\"

Obvious attempts fails

a, b, c, = \"yyy\"
a, b, c = \"yy         


        
相关标签:
2条回答
  • 2021-01-23 09:26

    No need to use tuple assignment here; the right-hand value is immutable, so you can just as well share the reference:

    a = b = c = 'yyy'
    

    This is not unintuitive at all, in my view, and the python compiler will only need to store one constant with the bytecode, while using tuple assignment requires an additional tuple constant:

    >>> def foo():
    ...     a, b, c = 'yyy', 'yyy', 'yyy'
    ... 
    >>> foo.__code__.co_consts
    (None, 'yyy', ('yyy', 'yyy', 'yyy'))
    >>> def bar():
    ...     a = b = c = 'yyy'
    ... 
    >>> bar.__code__.co_consts
    (None, 'yyy')
    

    Don't use this if the right-hand expression is mutable and you want a, b and c to have independent objects; use a generator expression then:

    a, b, c = ({} for _ in range(3))
    

    or better still, don't be so lazy and just type them out:

    a, b, c = {}, {}, {}
    

    It's not as if your left-hand assignment is dynamic.

    0 讨论(0)
  • 2021-01-23 09:47
    >>> a, b, c = ("yyy",)*3 
    

    The above construct is equivalent to a = b = c = "yyy" but requires creation of a tuple in memory, and still a,b,c are just references to the same object.

    For different id's use:

    a, b, c = ("yyy" for _ in xrange(3))
    

    This will not matter for string as they are immutable, but for mutable object they are different type of assignments.

    >>> a = b = c = []       #all of them are references to the same object
    >>> a is b
    True
    >>> a.append(1)          #Modifying one of them in-place affects others as well
    >>> a, b, c
    ([1], [1], [1])
    >>> a, b, c, = ([],)*3   #same as a = b = c = []
    >>> a is b
    True
    
    #Here a, b, c point to different objects
    >>> a, b, c, = ([] for _ in xrange(3))
    >>> a is b
    False
    >>> a.append(1)
    >>> a, b, c
    ([1], [], [])
    
    0 讨论(0)
提交回复
热议问题