Python - 使用没有重复单词的随机并从列表中选择一个备用单词



我正在使用随机模块来显示25个不同的单词。这些单词将显示在 5 x 5 的网格中。使用包含 26 个单词的文本文件,我希望在此网格中打印 25 个单词。但是,打印的单词不能重复,必须随机选择。那么我如何能够从该列表中获取备用单词以稍后在代码中使用?

with open("file.txt") as x:
        25words= x.read().splitlines()
def 5_by_5(l):
        grid = [listofwords[i:i+5] for i in range(0, len(listofwords), 5)]
        for l in grid:
            print("".join("{:10}".format(i) for i in l))
listofwords= [random.choice(25words) for x in range(25)]

因此,目前代码可以显示 5 x 5 网格,但单词是重复的。我如何获得它,以便网格中的每个单词都不同,然后将未使用的第 26 个单词标识为以后可以引用的东西?

您可以将列表视为队列。

抱歉,我不得不更改一些函数名称,否则它将无法运行。

import random
with open("file.txt") as x:
    words = x.read().splitlines()

def c_grid(l):
    grid = [listofwords[i:i + 5] for i in range(0, len(listofwords), 5)]
    for l in grid:
        print("".join("{:10}".format(i) for i in l))

listofwords = []
for i in range(25):
    myLen = len(words)
    res = random.choice(range(myLen))
    listofwords.append(words.pop(res))
print(listofwords)
c_grid(listofwords)

如果你更喜欢列表理解

import random
with open("file.txt") as x:
    words = x.read().splitlines()

def c_grid(l):
    grid = [listofwords[i:i + 5] for i in range(0, len(listofwords), 5)]
    for l in grid:
        print("".join("{:10}".format(i) for i in l))

listofwords = [words.pop(random.choice(range(len(words)))) for x in range(25)]
print(listofwords)
c_grid(listofwords)

我的结果:

['4', '23', '14', '2', '5', '22', '10', '9', '20', '8', '24', '18', '21', '25', '26', '19', '1', '11', '6', '17', '12', '15', '7', '3', '13']
4         23        14        2         5         
22        10        9         20        8         
24        18        21        25        26        
19        1         11        6         17        
12        15        7         3         13  

要获取剩余项目,请执行以下操作:

list_of_unused_words = [x for x in words]
if len(list_of_unused_words) == 1:
    list_of_unused_words = list_of_unused_words[0]
print(list_of_unused_words)

上面的代码列出了一个未使用的单词列表,以防不止一个单词并将其保存到列表中。如果只有一个单词,请将该单词另存为单个单词

最新更新