>>> A =205>>> B =-117>>> t = A ^ B # precomputed toggle constant>>> x = A>>> x ^= t # toggle>>> x-117>>> x ^= t # toggle>>> x205>>> x ^= t # toggle>>> x-117
(此想法由Nick Coghlan提交,后来由@zxxc推广。)
使用字典的解决方案
如果值是可哈希的,则可以使用字典:
>>> A ='xyz'>>> B ='pdq'>>> d ={A:B, B:A}>>> x = A>>> x = d[x]# toggle>>> x'pdq'>>> x = d[x]# toggle>>> x'xyz'>>> x = d[x]# toggle>>> x'pdq'
>>> A =[1,2,3]>>> B =[4,5,6]>>> x = A>>> x = B if x == A else A>>> x[4,5,6]>>> x = B if x == A else A>>> x[1,2,3]>>> x = B if x == A else A>>> x[4,5,6]
If the values are boolean, the fastest approach is to use the not operator:
>>> x = True
>>> x = not x # toggle
>>> x
False
>>> x = not x # toggle
>>> x
True
>>> x = not x # toggle
>>> x
False
Solution using subtraction
If the values are numerical, then subtraction from the total is a simple and fast way to toggle values:
>>> A = 5
>>> B = 3
>>> total = A + B
>>> x = A
>>> x = total - x # toggle
>>> x
3
>>> x = total - x # toggle
>>> x
5
>>> x = total - x # toggle
>>> x
3
The technique generalizes to any pair of integers. The xor-by-one step is replaced with a xor-by-precomputed-constant:
>>> A = 205
>>> B = -117
>>> t = A ^ B # precomputed toggle constant
>>> x = A
>>> x ^= t # toggle
>>> x
-117
>>> x ^= t # toggle
>>> x
205
>>> x ^= t # toggle
>>> x
-117
(This idea was submitted by Nick Coghlan and later generalized by @zxxc.)
Solution using a dictionary
If the values are hashable, you can use a dictionary:
>>> A = 'xyz'
>>> B = 'pdq'
>>> d = {A:B, B:A}
>>> x = A
>>> x = d[x] # toggle
>>> x
'pdq'
>>> x = d[x] # toggle
>>> x
'xyz'
>>> x = d[x] # toggle
>>> x
'pdq'
>>> A = [1,2,3]
>>> B = [4,5,6]
>>> x = A
>>> x = B if x == A else A
>>> x
[4, 5, 6]
>>> x = B if x == A else A
>>> x
[1, 2, 3]
>>> x = B if x == A else A
>>> x
[4, 5, 6]
Solution using itertools
If you have more than two values, the itertools.cycle() function provides a generic fast way to toggle between successive values:
Note that in Python 3 the next() method was changed to __next__(), so the first line would be now written as toggle = itertools.cycle(['red', 'green', 'blue']).__next__
If p is a boolean, this switches between true and false.
回答 2
这是另一种不直观的方法。优点是您可以循环多个值,而不仅仅是两个[0,1]
对于两个值(切换)
>>> x=[1,0]>>> toggle=x[toggle]
对于多个值(例如4)
>>> x=[1,2,3,0]>>> toggle=x[toggle]
我没想到这个解决方案也几乎是最快的
>>> stmt1="""
toggle=0
for i in xrange(0,100):
toggle = 1 if toggle == 0 else 0
""">>> stmt2="""
x=[1,0]
toggle=0
for i in xrange(0,100):
toggle=x[toggle]
""">>> t1=timeit.Timer(stmt=stmt1)>>> t2=timeit.Timer(stmt=stmt2)>>>print"%.2f usec/pass"%(1000000* t1.timeit(number=100000)/100000)7.07 usec/pass>>>print"%.2f usec/pass"%(1000000* t2.timeit(number=100000)/100000)6.19 usec/pass
stmt3="""
toggle = False
for i in xrange(0,100):
toggle = (not toggle) & 1
""">>> t3=timeit.Timer(stmt=stmt3)>>>print"%.2f usec/pass"%(1000000* t3.timeit(number=100000)/100000)9.84 usec/pass>>> stmt4="""
x=0
for i in xrange(0,100):
x=x-1
""">>> t4=timeit.Timer(stmt=stmt4)>>>print"%.2f usec/pass"%(1000000* t4.timeit(number=100000)/100000)6.32 usec/pass
The not operator negates your variable (converting it into a boolean if it isn’t already one). You can probably use 1 and 0 interchangeably with True and False, so just negate it:
toggle = not toggle
But if you are using two arbitrary values, use an inline if:
Surprisingly nobody mention good old division modulo 2:
In : x = (x + 1) % 2 ; x
Out: 1
In : x = (x + 1) % 2 ; x
Out: 0
In : x = (x + 1) % 2 ; x
Out: 1
In : x = (x + 1) % 2 ; x
Out: 0
Note that it is equivalent to x = x - 1, but the advantage of modulo technique is that the size of the group or length of the interval can be bigger then just 2 elements, thus giving you a similar to round-robin interleaving scheme to loop over.
Now just for 2, toggling can be a bit shorter (using bit-wise operator):
x = x ^ 1
回答 7
一种切换方式是使用多重分配
>>> a =5>>> b =3>>> t = a, b = b, a
>>> t[0]3>>> t = a, b = b, a
>>> t[0]5
The easiest way to toggle between 1 and 0 is to subtract from 1.
def toggle(value):
return 1 - value
回答 9
使用异常处理程序
>>>def toogle(x):...try:...return x/x-x/x
...exceptZeroDivisionError:...return1...>>> x=0>>> x=toogle(x)>>> x
1>>> x=toogle(x)>>> x
0>>> x=toogle(x)>>> x
1>>> x=toogle(x)>>> x
0
好吧,我是最糟糕的:
import math
import sys
d={1:0,0:1}
l=[1,0]def exception_approach(x):try:return x/x-x/x
exceptZeroDivisionError:return1def cosinus_approach(x):return abs( int( math.cos( x *0.5* math.pi )))def module_approach(x):return(x +1)%2def subs_approach(x):return x -1def if_approach(x):return0if x ==1else1def list_approach(x):global l
return l[x]def dict_approach(x):global d
return d[x]def xor_approach(x):return x^1def not_approach(x):
b=bool(x)
p=not b
return int(p)
funcs=[ exception_approach, cosinus_approach, dict_approach, module_approach, subs_approach, if_approach, list_approach, xor_approach, not_approach ]
f=funcs[int(sys.argv[1])]print"\n\n\n", f.func_name
x=0for _ in range(0,100000000):
x=f(x)
>>> toggle(1)Traceback(most recent call last):File"<stdin>", line 1,in<module>TypeError: descriptor 'conjugate' requires a 'complex' object but received a 'int'
对LHS和RHS进行更改:
>>> x +=1+2j>>> x
(3+5j)
…但是要小心操作RHS:
>>> z =1-1j>>> z +=2j>>> z
(1+1j)# whoops! toggled it!
>>> toggle(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: descriptor 'conjugate' requires a 'complex' object but received a 'int'
Perform changes to LHS and RHS:
>>> x += 1+2j
>>> x
(3+5j)
…but be careful manipulating the RHS:
>>> z = 1-1j
>>> z += 2j
>>> z
(1+1j) # whoops! toggled it!
Variables a and b can be ANY two values, like 0 and 1, or 117 and 711, or “heads” and “tails”. No math is used, just a quick swap of the values each time a toggle is desired.
a = True
b = False
a,b = b,a # a is now False
a,b = b,a # a is now True