2016-03-04 33 views
1

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

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个未被使用的单词标识为稍后可以引用的单词?

回答

2

你可以像列队一样对待你的列表。

对不起,我不得不改变一些函数名称,因为它不会运行。

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) 

上述C ode列出了未使用的单词,并列出不止一个单词,并将其保存到列表中。如果只有一个,那么将其保存为一个单词

+0

列表理解的作品谢谢。因此,如果使用这种方式,我将如何获得数字,在您的情况下,列表中的备用数字(第26个字)是一个单独的变量? – Coder

+0

所以你想剩下的项目还没有被用作变量? – Cripto

+0

是的,谢谢 – Coder