How to toggle a value in Python

后端 未结 17 962
梦谈多话
梦谈多话 2020-12-07 07:46

What is the most efficient way to toggle between 0 and 1?

17条回答
  •  眼角桃花
    2020-12-07 08:22

    You can make use of the index of lists.

    def toggleValues(values, currentValue):
        return values[(values.index(currentValue) + 1) % len(values)]
    
    > toggleValues( [0,1] , 1 )
    > 0
    > toggleValues( ["one","two","three"] , "one" )
    > "two"
    > toggleValues( ["one","two","three"] , "three")
    > "one"
    

    Pros: No additional libraries, self.explanatory code and working with arbitrary data types.

    Cons: not duplicate-save. toggleValues(["one","two","duped", "three", "duped", "four"], "duped") will always return "three"

提交回复
热议问题