Swapping 1 with 0 and 0 with 1 in a Pythonic way

前端 未结 16 1974
夕颜
夕颜 2020-12-23 13:50

In some part of my Python program I have a val variable that can be 1 or 0. If it\'s 1 I must change to 0, if it\'s 0 I must change to 1.

How do you do it in a Pytho

相关标签:
16条回答
  • 2020-12-23 14:37

    The shortest approach is using the bitwise operator XOR.

    If you want val to be reassigned:

    val ^= 1
    

    If you do not want val to be reassigned:

    val ^ 1
    
    0 讨论(0)
  • 2020-12-23 14:37

    Since True == 1 and False == 0 in python,

    you could just use var = not var

    It will just swap it.

    0 讨论(0)
  • 2020-12-23 14:39

    In your case I recommend the ternary:

    val = 0 if val else 1
    

    If you had 2 variables to swap you could say:

    (a, b) = (b, a)
    
    0 讨论(0)
  • 2020-12-23 14:44

    use np.where

    ex.

    np.where(np.array(val)==0,1,0)
    

    this gives 1 where val is 0 and gives 0 where val is anything else, in your case 1

    EDIT: val has to be array

    0 讨论(0)
提交回复
热议问题