Python: jak przełączać się między dwiema wartościami
Chcę przełączać się między dwiema wartościami w Pythonie, czyli między 0 a 1.
Na przykład, gdy uruchamiam funkcję po raz pierwszy, daje liczbę 0. Następnym razem daje 1. Trzeci raz jest z powrotem do zera, i tak dalej.
Przepraszam, jeśli to nie ma sensu, ale czy ktoś wie jak to zrobić?
13 answers
Użycie 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.
Zauważ, że jeśli potrzebujesz bardziej skomplikowanego cyklu niż [0, 1]
, rozwiązanie to staje się znacznie bardziej atrakcyjne niż inne zamieszczone tutaj...
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, ...
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-12 14:24:54
Możesz to osiągnąć za pomocą generatora takiego jak:
>>> def alternate():
... while True:
... yield 0
... yield 1
...
>>>
>>> alternator = alternate()
>>>
>>> alternator.next()
0
>>> alternator.next()
1
>>> alternator.next()
0
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-11 20:21:18
Przydatne może okazać się utworzenie aliasu funkcji w ten sposób:
import itertools
myfunc = itertools.cycle([0,1]).next
Then
myfunc() # -> returns 0
myfunc() # -> returns 1
myfunc() # -> returns 0
myfunc() # -> returns 1
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-11 20:36:58
Możesz użyć operatora mod (%
).
count = 0 # initialize count once
Then
count = (count + 1) % 2
Przełącza wartość count pomiędzy 0 a 1 za każdym razem, gdy ta instrukcja jest wykonywana. Zaletą tego podejścia jest to, że można przechodzić przez sekwencję wartości (w razie potrzeby) z 0 - (n-1)
, Gdzie n
jest wartością używaną z operatorem %
. I ta technika nie zależy od żadnych specyficznych funkcji/bibliotek Pythona.
Np.,
count = 0
for i in range(5):
count = (count + 1) % 2
print count
Daje:
1
0
1
0
1
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-11 20:38:06
W Pythonie True I False są liczbami całkowitymi (odpowiednio 1 i 0). Można użyć boolean (True lub False) i operatora not:
var = not var
Oczywiście, jeśli chcesz iterować pomiędzy innymi liczbami niż 0 i 1, Ta sztuczka staje się trochę trudniejsza.
Do spakowania tego do brzydkiej funkcji:
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-11 20:56:17
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-11 20:29:59
Użycie xor
działa i jest dobrym wizualnym sposobem przełączania między dwiema wartościami.
count = 1
count = count ^ 1 # count is now 0
count = count ^ 1 # count is now 1
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-12 10:48:11
var = 1
var = 1 - var
To oficjalny tricky way of doing it ;)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-11 20:21:20
Użycie podprogramu krotki:
value = (1, 0)[value]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-11 20:21:45
Używanie indeksów dolnych krotek jest dobrym sposobem przełączania między dwiema wartościami:
toggle_val = 1
toggle_val = (1,0)[toggle_val]
Jeśli owijasz funkcję wokół tego, będziesz miał ładny przełącznik przemienny.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-12 10:58:29
Aby przełączyć zmienną x pomiędzy dwoma dowolnymi (całkowitymi) wartościami, np. a i b, użycie:
# 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
Przykład:
Przełącz między 3 a 5
x = 3
x = 8 - x (now x == 5)
x = 8 - x (now x == 3)
x = 8 - x (now x == 5)
To działa nawet z łańcuchami (tak jakby).
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')
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-18 13:07:15
Proste i ogólne rozwiązanie bez użycia żadnego wbudowanego. Po prostu zachowaj śledzenie bieżącego elementu i wydrukuj / zwróć drugi, a następnie zmień status bieżącego elementu.
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
Wejście:
3 8
3
5
Wyjście:
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-21 06:43:33
Jeśli zmienna jest wcześniej zdefiniowana i chcesz, aby przełączała się między dwiema wartościami, możesz użyć a if b else C formularza:
variable = 'value1'
variable = 'value2' if variable=='value1' else 'value1'
Dodatkowo działa na Pythonie 2.5+ i 3.x
Https://docs.python.org/3/reference/expressions.html#conditional-expressions
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-03 17:12:46