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

前端 未结 16 1975
夕颜
夕颜 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:24

    I have swapped 0s and 1s in a list.

    Here's my list:

    list1 = [1,0,0,1,0]
    
    list1 = [i^1 for i in list1] 
    #xor each element is the list
    
    print(list1)
    

    So the outcome is: [0,1,1,0,1]

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

    If you want to be short:

    f = lambda val: 0 if val else 1
    

    Then:

    >>> f(0)
    1
    >>> f(1)
    0
    
    0 讨论(0)
  • 2020-12-23 14:31

    This isn't pythonic, but it is language neutral. Often val = 1 - val is simplest.

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

    Just another way:

    val = ~val + 2
    
    0 讨论(0)
  • 2020-12-23 14:35

    Just another possibility:

    i = (1,0)[i]
    

    This works well as long as i is positive, as dbr pointed out in the comments it doesn't work fail for i < 0.

    Are you sure you don't want to use False and True? It sounds almost like it.

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

    After seeing all these simpler answers i thought of adding an abstract one , it's Pythonic though :

    val = set(range(0,2)).symmetric_difference(set(range(0 + val, val + 1))).pop()
    

    All we do is return the difference of 2 sets namely [0, 1] and [val] where val is either 0 or 1.

    we use symmetric_difference() to create the set [0, 1] - [val] and pop() to assign that value to variable val.

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