簡體   English   中英

一旦顯示了相同的字母三遍,如何使此循環退出?

[英]How do I get this loop to quit once it has displayed the same letter three times?

所以我有這個完全搞砸的程序。 我想做的是,一旦顯示了三個相同的字母,就切斷循環。 到目前為止,我得到的是:

#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()

范圍是任意的。 僅用於測試目的。 我也嘗試過使用while循環,但是我也不知道如何殺死它。 它只是無限循環:

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

有什么建議么? 請不要討厭太多...

您需要保存隨機字符以進行比較,並保存遞增的計數器:

import random
A = 0
while A < 3:
    a = random.choice(letters)
    if a == 'A':
        A += 1
        print(a)

如果要跟蹤所有字母,請使用字典:

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

您必須以某種方式計算字母-如TigerhawkT3所示,字典非常適​​合此目的。 我在這里使用defaultdict,它對所有條目都有一個默認值-因為我使用int作為默認值,所以默認值為零。 這有點棘手,但是使我們不必初始化數組,如果值的數量事先未知或很大,這可能會很煩人。

如果要退出循環,請使用“ 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

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

計數器參考: https : //docs.python.org/2/library/collections.html#collections.Counter

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM