[英]How do I get this loop to quit once it has displayed the same letter three times?
So I have this totally screwed program. 所以我有这个完全搞砸的程序。 What I want to do is cut the loop off once it has displayed three of the same letters.
我想做的是,一旦显示了三个相同的字母,就切断循环。 So far what I have got is:
到目前为止,我得到的是:
#Declaring letter variable
letters = str('AEIOU')
A = 0
E = 0
I = 0
O = 0
U = 0
for i in range(0, 9):
print(random.choice(letters))
if (random.choice(letters)) == ('A'):
A + 1
print(random.choice(letters))
if A > 3:
quit()
The range is arbitrary. 范围是任意的。 Just for testing purposes.
仅用于测试目的。 I also tried using a while loop but I couldn't figure out how to kill it either.
我也尝试过使用while循环,但是我也不知道如何杀死它。 It just looped infinitely:
它只是无限循环:
A = 0
import random
while A < 3:
print(random.choice(letters))
if (random.choice(letters)) == ('A'):
A + 1
print(random.choice(letters))
if A > 3:
quit()
Any suggestions? 有什么建议么? Please don't hate too much...
请不要讨厌太多...
You need to save the random character for comparison, and save the incremented counter: 您需要保存随机字符以进行比较,并保存递增的计数器:
import random
A = 0
while A < 3:
a = random.choice(letters)
if a == 'A':
A += 1
print(a)
If you want to keep track of all the letters, use a dictionary: 如果要跟踪所有字母,请使用字典:
import random
letters = 'AEIOU'
d = {'A':0, 'E':0, 'I':0, 'O':0, 'U':0}
while 1:
letter = random.choice(letters)
d[letter] += 1
if d[letter] > 2:
break
You have to count the letters somehow - a dictionary is a good fit for this purpose, as TigerhawkT3 has shown. 您必须以某种方式计算字母-如TigerhawkT3所示,字典非常适合此目的。 I am using a defaultdict here, which has a default value for all entries - since I am using an int as default value, the default value is zero.
我在这里使用defaultdict,它对所有条目都有一个默认值-因为我使用int作为默认值,所以默认值为零。 This is somewhat more tricky, but saves us from initializing the array, which can be annoying if the amount of values is unknown in advance or large.
这有点棘手,但是使我们不必初始化数组,如果值的数量事先未知或很大,这可能会很烦人。
If you want to exit a loop use "break" - which breaks the current level of the loop - so for nested loops you would need mulitple breaks. 如果要退出循环,请使用“ break”-中断循环的当前级别-因此,对于嵌套循环,您需要多次中断。
import collections
import random
letters = str('AEIOU')
printed = collections.defaultdict(int)
while True:
letter = random.choice(letters)
print(letter)
printed[letter] += 1
if printed[letter] > 2:
break
Using Counter from python collections library, 使用python集合库中的Counter,
import random
from collections import Counter
letters = str('AEIOU')
counter = Counter()
limit = 3
while 1:
letter = random.choice(letters)
print(letter)
counter[letter] += 1
if counter[letter] >= limit:
break
Reference for Counter: https://docs.python.org/2/library/collections.html#collections.Counter 计数器参考: https : //docs.python.org/2/library/collections.html#collections.Counter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.