gpt4 book ai didi

python - 如何切换值?

转载 作者:IT老高 更新时间:2023-10-28 21:05:21 26 4
gpt4 key购买 nike

01 之间切换最有效的方法是什么?

最佳答案

使用 NOT 的解决方案

如果值是 bool 值,最快的方法是使用 not 运算符:

>>> x = True
>>> x = not x # toggle
>>> x
False
>>> x = not x # toggle
>>> x
True
>>> x = not x # toggle
>>> x
False

使用减法的解决方案

如果值是数字,那么从总数中减去是一种简单快捷的切换值的方法:

>>> 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

使用异或的解决方案

如果值在 01 之间切换,您可以使用 bitwise exclusive-or :

>>> x = 1
>>> x ^= 1
>>> x
0
>>> x ^= 1
>>> x
1

该技术推广到任何整数对。 xor-by-one 步骤被 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

(这个想法由 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'

使用条件表达式的解决方案

最慢的方法是使用 conditional expression :

>>> 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]

使用 itertools 的解决方案

如果您有两个以上的值,itertools.cycle()函数提供了一种在连续值之间切换的通用快速方法:

>>> import itertools
>>> toggle = itertools.cycle(['red', 'green', 'blue']).next
>>> toggle()
'red'
>>> toggle()
'green'
>>> toggle()
'blue'
>>> toggle()
'red'
>>> toggle()
'green'
>>> toggle()
'blue'

请注意,在 Python 3 中,next() 方法已更改为 __next__(),因此第一行现在将写为 toggle = itertools。 cycle(['red', 'green', 'blue']).__next__

关于python - 如何切换值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8381735/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com