Assign Many Variables at Once, Python

后端 未结 2 898
慢半拍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: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], [], [])
    

提交回复
热议问题