Python 单词 Scramble/Jumble - 这怎么打乱一个单词?

Python Word Scramble/Jumble - how does this scramble a word?

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

在下面用headers引用和分隔的部分中,我不明白为什么将单词的'scrambling'放入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)

让我们逐行查看 while 循环。

while word:

这只是 shorthand 表示 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] 表示 "the substring of word up to (but not including) the index position"。因此,如果 position 为 3,则 word[:position] 将作为字符串的 word 的前三个字符。同样,word[(position + 1):] 表示 "the substring of word starting at index position + 1"。

整个表达式最终为“word,索引 position 处的字符除外”,因为您将 word 的部分连接到 position word 的部分从 position + 1 开始。不幸的是,这是从 Python.

中的字符串中删除字符的最优雅的方法

总结一下:while循环随机选择原词的一个字符,加入到乱码中,从原词中删除。它会继续这样做,直到原件中没有剩余字符。