Python-如何对脚本构建的列表进行排序以复制另一个单词?

Python- How do I sort a list that the script is building to replicate another word?

我正在尝试执行一个绞刑游戏。我希望函数的一部分检查字母是否正确或不正确。当一个字母被发现是正确的,它将把字母放在一个"用过的字母"列表和一个"正确的字母列表"中,正确的字母列表将随着游戏的进行而建立。我想它排序的名单,以匹配隐藏的字,因为游戏正在进行。

例如,让我们用"硬件"这个词如果有人猜到"e,a,h",结果会是

1
correct = ["e","a","h"]

我想把清单分类,这样就可以了

1
correct = ["h","a","e"]

然后

推测r后的correct = ["h","a","r","a","e"]

我还需要知道它是否也会看到"A"在那里两次,并放置两次。

我的代码不允许你赢,但你可以输。这是一项正在进行的工作。我也不能把信放在左边的柜台上工作。我让代码打印列表,以检查是否添加了字母。它是。所以我不知道上面是什么。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def hangman():
    correct = []
    guessed = []
    guess =""
    words = ["source","alpha","patch","system"]
    sWord = random.choice(words)
    wLen = len(sWord)
    cLen = len(correct)
    remaining = int(wLen - cLen)
    print"Welcome to hangman.
"
    print"You've got 3 tries or the guy dies."
    turns = 3  

    while turns > 0:
        guess = str(raw_input("Take a guess. >"))

        if guess in sWord:          
            correct.append(guess)
            guessed.append(guess)  
            print"Great!, %d letters left." % remaining        
        else:
            print"Incorrect, this poor guy's life is in your hands."
            guessed.append(guess)
            turns -= 1
            print"You have %d turns left." % turns

    if turns == 0:
        print"HE'S DEAD AND IT'S ALL YOUR FAULT! ARE YOU HAPPY?"
        print"YOU LOST ON PURPOSE, DIDN'T YOU?!"

hangman()


我不完全清楚所期望的行为,因为:

correct = ["h","a","r","a","e"] after r has been guessed.

这很奇怪,因为a只被猜测过一次,但每次出现在hardware中都会出现。r也应该出现两次吗?如果这是正确的行为,那么可以使用非常简单的列表理解:

1
2
3
4
5
6
7
8
def result(guesses, key):
  print [c for c in key if c in guesses]

In [560]: result('eah', 'hardware')
['h', 'a', 'a', 'e']

In [561]: result('eahr', 'hardware')
['h', 'a', 'r', 'a', 'r', 'e']

迭代键中的字母,如果字母被用作"猜测",则将其包含在内。

您也可以通过使用以下命令,让它为未找到的字符插入一个占位符:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def result(guesses, key):
  print [c if c in guesses else '_' for c in key]
  print ' '.join([c if c in guesses else '_' for c in key])

In [567]: result('eah', 'hardware')
['h', 'a', '_', '_', '_', 'a', '_', 'e']
h a _ _ _ a _ e

In [568]: result('eahr', 'hardware')
['h', 'a', 'r', '_', '_', 'a', 'r', 'e']
h a r _ _ a r e

In [569]: result('eahrzw12', 'hardware')
['h', 'a', 'r', '_', 'w', 'a', 'r', 'e']
h a r _ w a r e