首页 > 解决方案 > 随机化项目和循环列表(Python)

问题描述

你们大家,我正在努力减轻我的一些工作,从面对面的教学环境迁移到至少在接下来的三个月内偏远的环境。为此,我正在尝试为测验创建符合条件的词汇的随机列表。我可以让它为相同数量的测验生成多达十八组单词,但我似乎在检查随机选择的单词是否已经是该测验的一部分,即我得到了大量的重复。由于每天教一个单词,这意味着第一个双周测验将有十个符合条件的单词;第二个,二十个字;第三,三十个字;等请参阅下面的代码,并提前感谢您的帮助!

import random

all_words = "salutation feasible obnoxious depict resolve surmise assumption kindle intimidate jurisdiction allege characterize similar novice perceive condemn avid concise quench abrasive inevitable universal exonerate endeavor competent bamboozle simulate jeopardize prospective mutiny ubiquity integrate prevalent audacious reverberate corroborate feasible theory devour calamity boisterous amiss bizarre punctual simultaneous proprietor component famished significant conclude abdicate boycott consult rebuff eccentric imperative confront naive tirade ludicrous conscientious inhabitant confiscate admonish acknowledge embark prominent evoke libel modify imminent affiliation dawdle encompass indifferent perspective bias vitality necessity connotation despondent grieve gruesome perish devious sovereign propaganda construct prudent viewpoint liaison negligent relinquish mitigate formidable chronological commence ambiguous suspense consistent temperament impel assimilate gracious estimate apathy resilient opposition elapse killjoy obsolete signify satire hypothesis tumult harmonious fictitious authentic anonymous attribute procedure conclusive thrive capable interrogate legendary spontaneous addict merge evidence mandatory demeanor rebel despicable belligerent agitate oppress rebuke anarchy recur consecutive derogatory anthology valor elegant transit acquire authority contrast tentative profound specific exposition conjecture exuberant diversity abhor irate haughty irrelevant cause hospitable quaint inspire derive impartial industrious pseudonym omit prediction source apprehend bisect focus antagonize adequate bewildered correspond precise eligible".split(" ")

for week in range(1, 2):
    print("---------------------")
    print("Quiz #" + str(week))
    print("---------------------")
    print("Word\t\tID")
    print("---------------------")

    for word in range(1, 10+1):
        random_words = []
        
        random_word = all_words[random.randrange(0, (week*10))]
        
        # checks to see if random word is already
        # part of the words on the upcoming quiz
        if random_word not in random_words:
            random_words.append(random_word)

        # test to see if any of the ids match
        # and that they fall within the eligible
        # range for vocab words already taught
        for test in random_words:
            print('{:15} {}'.format(test, all_words.index(test)+1))
    print("---------------------")

标签: pythonlist

解决方案


您可能想尝试使用random.sample(all_words, 10)并循环以将输出扩展到随后的几周(将 10 更改为所需的字数)。你需要import random先。


推荐阅读