【问题标题】:Random Word from Different Lists using the random module使用 random 模块从不同列表中随机词
【发布时间】:2021-01-26 19:30:25
【问题描述】:

我正在尝试做一个带有一些曲折的刽子手游戏,我使用随机模块从几个具有不同主题的文本文件中进行随机选择,例如动物、食物、国家.. 我转移到不同的列表和我不知道如何让 python 现在从所有列表中选择一个随机单词。我的意思是我希望它选择一个随机列表并从列表中选择一个随机词我还没有在互联网上找到任何解决方案但也许我只是愚蠢

import random

colors_txt = open('colors.txt', 'r')
color_lst = []
for color in colors_txt:
    color_lst.append(color.replace('\n', ''))

random_color = random.sample(color_lst, 1)

这是例如我知道有函数 random.choice() 的代码,但我只是使用了这个

【问题讨论】:

  • 所以您有一个列表列表,并且您想从该列表中的随机列表中选择一个随机项目?
  • 不,我有 4 个只有很多单词的列表,我想从 4 个随机列表中选择一个随机单词

标签: python list random


【解决方案1】:

我想这就是你要问的

import random

lists = [[...], [...], ...]

chosenList = random.choice(lists)
output = random.choice(chosenList)

【讨论】:

    【解决方案2】:

    试试这个:

    import random
    
    lists = [...] #your lists as a list of lists
    #picks a list randomly
    randomList = random.choice(lists)
    #picks an item in the randomly found list
    result = random.choice(randomList)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-05
      • 2018-08-18
      • 2013-12-17
      • 1970-01-01
      • 2015-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多