Tuple unpacking order changes values assigned

前端 未结 4 1488
温柔的废话
温柔的废话 2020-12-03 06:36

I think the two are identical.

nums = [1, 2, 0]    
nums[nums[0]], nums[0] = nums[0], nums[nums[0]]    
print nums  # [2, 1, 0]

nums = [1, 2, 0]    
nums[0]         


        
4条回答
  •  醉梦人生
    2020-12-03 07:02

    You can define a class to track the process:

    class MyList(list):
        def __getitem__(self, key):
            print('get ' + str(key))
            return super(MyList, self).__getitem__(key)
        def __setitem__(self, key, value):
            print('set ' + str(key) + ', ' + str(value))
            return super(MyList, self).__setitem__(key, value)
    

    For the first method:

    nums = MyList([1, 2, 0])
    nums[nums[0]], nums[0] = nums[0], nums[nums[0]]
    

    the output is:

    get 0
    get 0
    get 1
    get 0
    set 1, 1
    set 0, 2
    

    While the second method:

    nums = MyList([1, 2, 0])
    nums[0], nums[nums[0]] = nums[nums[0]], nums[0]
    

    the output is:

    get 0
    get 1
    get 0
    set 0, 2
    get 0
    set 2, 1
    

    In both methods, the first three lines are related to tuple generation while the last three lines are related to assignments. Right hand side tuple of the first method is (1, 2) and the second method is (2, 1).

    In the assignment stage, first method get nums[0] which is 1, and set nums[1] = 1, then nums[0] = 2, second method assign nums[0] = 2, then get nums[0] which is 2, and finally set nums[2] = 1.

提交回复
热议问题