【问题标题】:Make sure that an output of a string is a certain amount of words确保字符串的输出是一定数量的单词
【发布时间】:2021-02-14 09:16:16
【问题描述】:

所以我试图制作一个单词列表并将其随机化,列表将所有单词返回,但列表是 14 个单词,我总是希望输出为 12 个单词。这是非常困难的,因为镜头数会发生变化,这甚至可能吗?这是我的代码,它运行顺利,但我不知道如何在打印的末尾删除 2 个单词,因为字符会发生变化。

words = ["seed", "rest", "sad", "running", "water", "disease", "militia", "apple", "banana", "grape", "program", "stove", "prints", "forrest"]       
randomizing_words = random.sample(words, len(words))
linecount = len(randomizing_words)
       if linecount >= 12:
           print('removing last 2 to make it 12 words')
          # (WHAT DO I DO HERE)
       else:
           pass

我觉得这可能是不可能的。任何提示都会有所帮助

【问题讨论】:

    标签: python-3.x list


    【解决方案1】:

    无论如何都只返回列表的前 12 个元素:

    import random    # imports random
    
    words = ["seed", "rest", "sad", "running", "water", "disease", "militia", "apple", "banana", "grape", "program", "stove", "prints", "forrest"]    # initial list
    random.shuffle(words)    # randomizes list
    print(words[:12])    # prints (you can change this to return) first 12 elements of the list
    

    【讨论】:

      猜你喜欢
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-17
      • 2018-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多