【问题标题】:Python - Using Random with No Repeated Words and Selecting a Spare Word from a ListPython - 使用无重复词的随机词并从列表中选择一个备用词
【发布时间】:2016-03-04 21:36:43
【问题描述】:

我正在使用随机模块来显示 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 个单词识别为以后可以引用的东西?

【问题讨论】:

    标签: python list random


    【解决方案1】:

    您可以将您的列表视为队列。

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

    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 个单词)成为一个单独的变量?
    • 所以你想要剩余的没有被用作变量的项目?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多