web-dev-qa-db-ja.com

Python:2つの値を切り替える方法

Pythonの2つの値、つまり0と1の間を切り替えたいです。

たとえば、最初に関数を実行すると、数値0が生成されます。次回は、1が生成されます。3回目には、ゼロに戻ります。

これが意味をなさない場合は申し訳ありませんが、誰かがこれを行う方法を知っていますか?

34
Yngve

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, ...
57
Platinum Azure

これは、次のようなジェネレーターで実現できます。

>>> def alternate():
...   while True:
...     yield 0
...     yield 1
...
>>>
>>> alternator = alternate()
>>>
>>> alternator.next()
0
>>> alternator.next()
1
>>> alternator.next()
0
45
g.d.d.c

次のような関数エイリアスを作成すると便利です。

import itertools
myfunc = itertools.cycle([0,1]).next

その後

myfunc()    # -> returns 0
myfunc()    # -> returns 1
myfunc()    # -> returns 0
myfunc()    # -> returns 1
18
Hugh Bothwell

mod(_%_)演算子を使用できます。

_count = 0  # initialize count once
_

その後

_count = (count + 1) % 2
_

このステートメントが実行されるたびに、countの値が0と1の間で切り替わります。このアプローチのadvantageは、0 - (n-1)から一連の値(必要な場合)を循環できることです。ここで、nは_%_演算子。そしてこのテクニックは、Python特定の機能/ライブラリに依存しません。

例えば。、

_count = 0

for i in range(5):
     count = (count + 1) % 2
     print count
_

与える:

_1
0
1
0
1
_
17
Levon

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
9
mgilson
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
8
Marcin

xorを使用すると機能します。これは、2つの値を切り替える視覚的な方法です。

count = 1
count = count ^ 1 # count is now 0
count = count ^ 1 # count is now 1
6
var = 1
var = 1 - var

これが公式のトリッキーな方法です;)

6
SetSlapShot

変数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')
4
ack

タプル添え字トリックの使用:

value = (1, 0)[value]
3
Shawn Chin

タプル添え字の使用は、2つの値を切り替える1つの良い方法です。

toggle_val = 1

toggle_val = (1,0)[toggle_val]

これに関数をラップすると、Nice代替スイッチができます。

2
octopusgrabbus

ビルトインを使用しないシンプルで一般的なソリューション。現在の要素を追跡し、他の要素を印刷/返却して、現在の要素のステータスを変更するだけです。

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

1
Gautam Seth

変数が以前に定義されていて、2つの値を切り替えたい場合は、a if b else c形式を使用できます。

variable = 'value1'
variable = 'value2' if variable=='value1' else 'value1'

さらに、Python 2.5+ and 3.x

https://docs.python.org/3/reference/expressions.html#conditional-expressions

0
Jorge Valentini

あなたがどんな言語でもできる一つのクールな方法:

variable = 0
variable = abs(variable - 1)    // 1
variable = abs(variable - 1)    // 0

0
SoloVen