簡體   English   中英

如何編碼,以便程序找到多個實例-Python

[英]How to code so the program finds multiple instances - Python

我有以下代碼:

Words = ['python','candy', 'banana', 'chicken', 'pizza', 'calculus',
     'cheeseburger', 'binder', 'computer', 'pencil', 'school'
     'artist', 'soccer', 'tennis', 'basketball', 'panda',
     'zebra', 'horse', 'cereal', 'alphabet', 'understand']

number = raw_input('Enter a 1 through 20: ')
x = list()
find = list(Words[int(number)-1])
notherword = list(Words[int(number)-1])
l = list(len(find)*'_')
print 'Your word is', len(find)*'_ '
playing = True
while playing:
    letter = raw_input('Please pick a letter ')
    if letter in find:
        a = find.index(str(letter))
        l[int(a)] = letter
        q = (' ')
        j = q.join(l)
        print j
        find[a] = ('_')
        if l == notherword:
            print 'You win!!!'
            playing = False
    else:
        print 'Strike ' +str(len(x)+1) +str('.') +str(' Not a letter in the word')
        x.append(letter)
        if len(x) > 4:
            print 'Game Over x('
            playing = False

這是一個子手游戲。 您首先選擇一個數字,然后該數字與單詞相對應,然后開始執行man子手游戲。 但是,當我執行“香蕉”一詞時,它只會找到第一個a,而找不到另一個a。 我該如何編碼,以便它可以一次找到多個實例,從而使其運行正常?

使用更新的代碼進行編輯

一個簡單的解決方案是將找到的字母替換為其他字母,這樣就不會出現兩次。 您可以使用列表理解來獲取給定字母的所有索引:

if letter in find:
    # use a list comprehension to get the index of all occurrences of a given letter
    indexes = [i for i, char in enumerate(find) if char == letter]
    # update found and l accordingly
    for i in indexes:
        find[i] = None
        l[i] = letter

然后檢查他們是否贏了,您可以改為:

if '_' not in l:
    print 'You win!!!'

您還需要在while循環之外創建x ,而不是在玩家每次猜錯時都重新創建x ,這樣玩家實際上就可能輸掉(您也可以while True和break時執行,而不是使用playing變量):

x = list()
while True:
    ...
    else:
        print 'Not a letter in the word'
        x.append(letter)
        if len(x) > 4:
            print 'Game Over'
            break

順便說一句,您不需要在循環中使用strint 另外''.join()是一個通用的Python習慣用法,您應該改用它。 考慮到以上因素,這是修訂版:

Words = ['python','candy', 'banana', 'chicken', 'pizza', 'calculus',
     'cheeseburger', 'binder', 'computer', 'pencil', 'school'
     'artist', 'soccer', 'tennis', 'basketball', 'panda',
     'zebra', 'horse', 'cereal', 'alphabet', 'understand']

number = raw_input('Enter a 1 through 20: ')

find = list(Words[int(number)-1])
l = list(len(find)*'_')
x = list()

print 'Your word is', len(find)*'_ '

while True:
    letter = raw_input('Please pick a letter ')
    if letter in find:
        indexes = [i for i, char in enumerate(find) if char == letter]
        for i in indexes:
            find[i] = None
            l[i] = letter
        print ' '.join(l)
        if '_' not in l:
            print 'You win!!!'
            break
    else:
        print 'Not a letter in the word'
        x.append(letter)
        if len(x) > 4:
            print 'Game Over'
            break

您必須使用循環來依次匹配每個a:

while playing:
    letter = raw_input('Please pick a letter ')
    while letter in find:
        a = find.index(letter)

        # Clear the letter so we can match the next instance.
        find[a] = None 

        l[a] = letter
        q = (' ')
        j = q.join(l)
        print j
        if l == find:
            print 'You win!!!'
            playing = False
    else:
        ....

[這不是通常要做的所有事情,但是您可以在Python中結合使用else。 ]

同樣,您應該在游戲循環上方設置x = list(),就這樣,您永遠不會輸。

你應該更換這個

if letter in find:
    a = find.index(str(letter))
    l[int(a)] = letter

有了這個

letter_in_word = False
for a,c in enumerate(find):
    if c == letter:
        l[a] = letter
        letter_in_word = True
if letter_in_word:
    ...
else:
    ...

代替

a = find.index(str(letter))
l[int(a)] = letter

嘗試這個

[l.__setitem__(pos, letter) for pos in range(len(find)) if find[pos]==letter]

基本上,如果所選的字母位於需要找到的單詞中的那個位置,則對單詞進行迭代將其設置為所選的字母。

我通常不會只為某人編寫代碼,但是有時這是說明各種技術的最佳方法。 請仔細研究。 請注意,如果我實際上是在編寫此代碼,則其中將不會包含任何注釋。 這些技術是標准的。

# Let's wrap the "main" code in a function for cleanliness.
def main():
    words = [
        'python','candy', 'banana', 'chicken', 'pizza', 'calculus',
        'cheeseburger', 'binder', 'computer', 'pencil', 'school'
        'artist', 'soccer', 'tennis', 'basketball', 'panda',
        'zebra', 'horse', 'cereal', 'alphabet', 'understand'
    ]
    import random
    word = random.choice(words)
    # Instead of using a list of characters for what's been
    # guessed, a string will work fine. We can iterate over it
    # the same way.
    guessed = '_' * len(word)
    failures = '' # used to be 'x'. Use descriptive names.

    # To break out of a loop, we can use the 'break' keyword.
    # So we don't really need a separate variable to control the loop.
    # We want to show status every time through the loop, so we put that
    # inside the loop.
    while True:
        print guessed
        # Note the idiomatic way we use to intersperse spaces into the word.
        print 'Not in the word:', ' '.join(failures)
        letter = raw_input('Please pick a letter: ')
        # We use the following trick to update the guess status:
        # 1) We'll create a second string that contains the guessed
        # letter in each place where it should appear.
        # 2) If that string differs from the old guess, then we
        # must have guessed a letter correctly. Otherwise, the letter
        # is not in the word.
        # We take pairs of letters from `word` and `guessed` using the
        # zip() function, and use the letter from the word if it's matched,
        # and otherwise keep the letter from the old guess. `''.join` joins
        # up all the chosen letters to make a string again.
        new_guess = ''.join(
            w if w == letter else g
            for (w, g) in zip(word, guessed) 
        )
        if new_guess == word:
            print 'You win!!!'
            break
        elif new_guess != guessed:
            print "Yes, '%s' is in the word." % letter
        else:
            # Instead of having the ugly '+1' in the logic for counting misses,
            # just count the misses *after* processing this one. Also note how
            # the string formatting works.
            failures += letter
            print "Strike %d. '%s' is not in the word." % (len(failures), letter)
            if len(failures) > 4:
                print 'Game Over x('
                break

暫無
暫無

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

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