如何编写代码以便程序查找多个实例-Python

如何编写代码以便程序查找多个实例-Python,python,Python,我有以下代码: Words = ['python','candy', 'banana', 'chicken', 'pizza', 'calculus', 'cheeseburger', 'binder', 'computer', 'pencil', 'school' 'artist', 'soccer', 'tennis', 'basketball', 'panda', 'zebra', 'horse', 'cereal', 'alphabet', 'underst

我有以下代码:

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
这是一个刽子手游戏。首先选择一个数字,然后该数字与单词对应,然后开始一场绞刑游戏。但是当我用香蕉这个词时,它只找到第一个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
,而不是每次玩家猜错时都重新创建它,这样玩家实际上可能会输(您也可以在
while True
和break中执行
操作,而不是使用
playing
变量):

另外,您不需要在循环中使用
str
int
。另外,
'.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

一个简单的解决方案是用其他东西替换找到的字母,这样它们就不会被发现两次。您可以使用列表获取给定字母的所有索引:

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
,而不是每次玩家猜错时都重新创建它,这样玩家实际上可能会输(您也可以在
while True
和break中执行
操作,而不是使用
playing
变量):

另外,您不需要在循环中使用
str
int
。另外,
'.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(),这样您就永远不会输。

您必须使用循环依次匹配每个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:
    ...

你应该把这个换掉

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]
基本上,如果所选字母位于需要查找的单词中的该位置,它会迭代该单词,将该位置的字母设置为所选字母。

而不是

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

我通常不会只为某人编写代码,但有时这是演示各种技术的最佳方式。请仔细研究。请注意,如果我真的在写这段代码,它不会有任何这些注释;这些技术是标准的

# 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


粘贴在此处的代码已损坏:缩进错误。你能修复它吗?对不起,哪个部分看起来很好大的红旗是下面的一行“if letter in find:”没有缩进。这就是问题所在:我不知道哪个部分坏了,因为错误可能在很多地方:)复制并粘贴上面的代码,然后运行它,你会看到问题所在。你的代码,正如粘贴在这里的一样,破损:其压痕错误。你能修复它吗?对不起,哪个部分看起来很好大的红旗是下面的一行“if letter in find:”没有缩进。这就是重点:我不知道哪个部分坏了,因为错误可能在很多地方:)复制并粘贴上面的代码,然后运行它,你会发现问题出在哪里。但是如果我删除了这个字母,那么索引号会改变,程序会向上旋转,但是在这种情况下,下一个字母的索引会出错,不是吗?新的index调用将返回单词
bnana
中下一个a的索引。我有点修改了你(zeekay)的想法,使它有两个相同单词的列表,并替换找到的每个字母。它工作了,但没有找到多个实例。对于香蕉,我必须输入三个不同的时间哦,你是对的,我没有完全阅读你的代码。我用一个简单的方法更新了我的答案。对不起,我想我不知道怎么玩刽子手。我再次更新了我的答案。但是如果我删除了这个字母,那么索引号会改变,程序会向上旋转,但在这种情况下,下一个字母的索引会出错,不是吗?新的index调用将返回单词
bnana
中下一个a的索引。我有点修改了你(zeekay)的想法,使它有两个相同单词的列表,并替换找到的每个字母。它工作了,但没有找到多个实例。对于香蕉,我必须输入三个不同的时间哦,你是对的,我没有完全阅读你的代码。我用一个简单的方法更新了我的答案。对不起,我想我不知道怎么玩刽子手。我再次更新了我的答案。我用for循环尝试了类似的方法。它和for循环做的是一样的,它确实找到了多个实例,但它通过else部分运行,并打印出j,字母在单词中的次数。我在for循环中尝试过类似的方法。它和for循环做的是一样的,它确实找到了多个实例,但是它通过else部分运行,并打印出j和tim的数量