zoukankan      html  css  js  c++  java
  • Python中四种交换两个变量的值的方法

    Python中四种交换两个变量的值的方法

    方法一:(所有语言都可以通过这种方式进行交换变量)
      通过新添加中间变量的方式,交换数值.
      下面通过一个demo1函数进行演示: 

    def demo1(a,b):
        temp = a
        a = b
        b = temp
        print(a,b)

    方法二:(此方法是Python中特有的方法)

        直接将a, b两个变量放到元组中,再通过元组按照index进行赋值的方式进行重新赋值给两个变量。

        下面通过一个demo2函数进行演示:

    def demo2(a,b):
        a,b = b,a
        print(a,b)

    方法三:

      通过简单的逻辑运算进行将两个值进行互换

      下面通过一个demo3函数进行演示:

    def demo3(a, b):
        a = a + b
        b = a - b
        a = a - b
        print(a, b)

    方法四:

      通过异或运算 将两个值互换 异或运算的原理是根据二进制中的  "1^1=0 1^0=1 0^0=0"

      下面通过一个demo4函数进行演示:

    def demo4(a,b):
        a = a^b  
        b = a^b  # b = (a^b)^b = a
        a = a^b  # a = (a^b)^a = b
        print(a,b)
  • 相关阅读:
    COM组件
    【游戏引擎架构】入门(一)
    UNICODE字符串
    Python随笔10
    Python随笔9-函数
    Python随笔7
    Python随笔6
    Python随笔5
    Python随笔4
    Python随笔3
  • 原文地址:https://www.cnblogs.com/aydenwang/p/9398826.html
Copyright © 2011-2022 走看看