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

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

    The most pythonic way would probably be

    int(not val)
    

    But a shorter way would be

    -~-val
    
    0 讨论(0)
  • 2020-12-23 14:18

    To expand upon the answer by "YOU", use:

    int(not(val))
    

    Examples:

    >>> val = 0
    >>> int(not(val))
    1
    >>> val = 1
    >>> int(not(val))
    0
    

    Note that this answer is only meant to be descriptive, not prescriptive.

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

    Here's a simple way:

    val = val + 1 - val * 2
    

    For Example:

    If val is 0

    0+1-0*2=1
    

    If val is 1

    1+1-1*2=0
    
    0 讨论(0)
  • 2020-12-23 14:19

    Function with mutable argument. Calling the swaper() will return different value every time.

    def swaper(x=[1]):
        x[0] ^= 1
        return x[0]
    
    0 讨论(0)
  • 2020-12-23 14:20

    (0,1)[not val] flips the val from 0 to 1 and vice versa.

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

    Your way works well!

    What about:

    val = abs(val - 1)
    

    short and simple!

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