Python-使用不重复单词的Random并从列表中选择一个备用单词

Python-使用不重复单词的Random并从列表中选择一个备用单词,python,list,random,Python,List,Random,我使用随机模块来显示25个不同的单词。这些单词将以5乘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 rang

我使用随机模块来显示25个不同的单词。这些单词将以5乘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乘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)

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

列表理解有效谢谢。那么使用这个,我怎么才能得到这个数字,在你的例子中,这个数字在列表中是多余的(第26个单词),作为一个单独的变量?那么你想要剩下的没有被用作变量的项目吗?