Pythonの2つの値、つまり0と1を切り替えたい。
たとえば、関数を最初に実行すると、数値は0になります。次回は、1になります。3回目は、ゼロに戻ります。
これが意味をなさない場合は申し訳ありませんが、誰かがこれを行う方法を知っていますか?
使用itertools.cycle()
:
from itertools import cycle
myIterator = cycle(range(2))
myIterator.next() # or next(myIterator) which works in Python 3.x. Yields 0
myIterator.next() # or next(myIterator) which works in Python 3.x. Yields 1
# etc.
より複雑なサイクルが必要な場合[0, 1]
、このソリューションはここに掲載されている他のソリューションよりもはるかに魅力的になることに注意してください...
from itertools import cycle
mySmallSquareIterator = cycle(i*i for i in range(10))
# Will yield 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 0, 1, 4, ...
あなたはこのようなジェネレーターでそれを達成することができます:
>>> def alternate():
... while True:
... yield 0
... yield 1
...
>>>
>>> alternator = alternate()
>>>
>>> alternator.next()
0
>>> alternator.next()
1
>>> alternator.next()
0
%
mod( )演算子を使用できます。
count = 0 # initialize count once
それから
count = (count + 1) % 2
このステートメントが実行されるたびに、countの値が0と1の間で切り替わります。このアプローチの利点は、オペレーターで使用する値が0 - (n-1)
どこにあるかから、(必要に応じて)一連の値を循環できることです。また、この手法はPython固有の機能/ライブラリに依存しません。n
%
例えば、
count = 0
for i in range(5):
count = (count + 1) % 2
print count
与える:
1
0
1
0
1
次のような関数エイリアスを作成すると便利な場合があります。
import itertools
myfunc = itertools.cycle([0,1]).next
それから
myfunc() # -> returns 0
myfunc() # -> returns 1
myfunc() # -> returns 0
myfunc() # -> returns 1
Pythonでは、TrueとFalseは整数(それぞれ1と0)です。ブール値(TrueまたはFalse)とnot演算子を使用できます。
var = not var
もちろん、0と1以外の数値を繰り返し処理する場合、このトリックは少し難しくなります。
これを明らかに醜い関数に詰め込むには:
def alternate():
alternate.x=not alternate.x
return alternate.x
alternate.x=True #The first call to alternate will return False (0)
mylist=[5,3]
print(mylist[alternate()]) #5
print(mylist[alternate()]) #3
print(mylist[alternate()]) #5
from itertools import cycle
alternator = cycle((0,1))
next(alternator) # yields 0
next(alternator) # yields 1
next(alternator) # yields 0
next(alternator) # yields 1
#... forever
var = 1
var = 1 - var
それはそれを行うための公式のトリッキーな方法です;)
作品を使用xor
し、2つの値を切り替えるための優れた視覚的な方法です。
count = 1
count = count ^ 1 # count is now 0
count = count ^ 1 # count is now 1
変数xを2つの任意の(整数)値(aとbなど)の間で切り替えるには、次を使用します。
# start with either x == a or x == b
x = (a + b) - x
# case x == a:
# x = (a + b) - a ==> x becomes b
# case x == b:
# x = (a + b) - b ==> x becomes a
例:
3と5の間で切り替えます
x = 3
x = 8 - x (now x == 5)
x = 8 - x (now x == 3)
x = 8 - x (now x == 5)
これは文字列(一種)でも機能します。
YesNo = 'YesNo'
answer = 'Yes'
answer = YesNo.replace(answer,'') (now answer == 'No')
answer = YesNo.replace(answer,'') (now answer == 'Yes')
answer = YesNo.replace(answer,'') (now answer == 'No')
タプル添え字トリックの使用:
value = (1, 0)[value]
タプル添え字を使用することは、2つの値を切り替える良い方法の1つです。
toggle_val = 1
toggle_val = (1,0)[toggle_val]
この周りに関数をラップすると、素敵な交互のスイッチができます。
組み込みを使用しないシンプルで一般的なソリューション。現在の要素を追跡し、もう1つを印刷/返却してから、現在の要素のステータスを変更するだけです。
a, b = map(int, raw_input("Enter both number: ").split())
flag = input("Enter the first value: ")
length = input("Enter Number of iterations: ")
for i in range(length):
print flag
if flag == a:
flag = b;
else:
flag = a
入力:
3 8
3
5
出力:
3
8
3
8
3
Means numbers to be toggled are 3 and 8
Second input, is the first value by which you want to start the sequence
And last input indicates the number of times you want to generate
変数が以前に定義されていて、2つの値を切り替えたい場合は、a if belsec形式を使用できます。
variable = 'value1'
variable = 'value2' if variable=='value1' else 'value1'
さらに、Python2.5以降および3.xで動作します
https://docs.python.org/3/reference/expressions.html#conditional-expressions
どの言語でもできるクールな方法の1つ:
variable = 0
variable = abs(variable - 1) // 1
variable = abs(variable - 1) // 0