0

我在这里有一个 python 程序可以解读一个单词,但我不确定特定部分发生了什么。

在下面由标题块引用和分隔的部分中,我不明白为什么将单词的“加扰”放入 while 循环中 - 如果没有循环,它不能工作吗?另外,有人可以解释一下while循环(while word:)中发生的一切吗?

import random
words = ('coffee', 'phone', 'chair', 'alarm')
word = random.choice(words)

correct = word
scramble = ""

while word:
    position = random.randrange(len(word))
    scramble += word[position]
    word = word[:position] + word[(position + 1):]

print("The scrambled word is: ", scramble)
answer = input("What's your guess?: ")

def unscramble(answer):
    while answer != correct and answer != "":
        print("Sorry, incorrect.")
        answer = input("Try again: ")
    if answer == correct:
        print("Good job, that is correct!")

unscramble(answer)
4

1 回答 1

0

让我们看一下 while 循环,一次一行。

while word:

这只是说的简写while len(word) > 0。这意味着循环将继续,直到word为空。

    position = random.randrange(len(word))

此行使用标准库random.randrange函数来获取介于 0 和(含)之间的(伪)随机数len(word) - 1

    scramble += word[position]

这里,单词中随机位置的字符被添加到加扰单词中。

    word = word[:position] + word[(position + 1):]

最后,这一行使用切片从原始单词中删除随机选择的字符。该表达式的word[:position]意思是“word最多(但不包括)索引的子字符串position”。因此,如果position是 3,则将word[:position]word 的前三个字符作为字符串。同样,word[(position + 1):]表示“word从索引开始的子字符串position + 1”。

整个表达式最终成为“word除了 index 处的字符position”,因为您将wordup toposition的部分与wordstart at的部分连接起来position + 1。不幸的是,这是在 Python 中从字符串中删除字符的最优雅的方式。

总结一下:while 循环从原始单词中选择一个随机字符,将其添加到打乱的单词中,然后将其从原始单词中删除。它会继续这样做,直到原稿中没有字符为止。

于 2017-04-12T03:03:00.953 回答