【问题标题】:How to randomly choose a list out of 4 lists?如何从 4 个列表中随机选择一个列表?
【发布时间】:2021-01-23 17:20:59
【问题描述】:

我有 3 个列表,每次我想随机选择任何一个项目。我该怎么做?

fruit_list = ['apple', 'orange', 'mango']
transport_list = ['car', 'bus', 'ship']
animal_list = ['cat', 'dog', 'Tiger']

【问题讨论】:

标签: python random


【解决方案1】:

您可以使用random.choice()

将您的列表和合并列表中的示例添加在一起:

import random

fruit_list = ['apple', 'orange', 'mango']
transport_list = ['car', 'bus', 'ship']
animal_list = ['cat', 'dog', 'Tiger']

l = fruit_list + transport_list + animal_list

print(random.choice(l))

【讨论】:

    【解决方案2】:

    python 中有一个名为 random 的模块。你可以用谷歌搜索,但这里是你从列表中随机选择元素的方法。

    import random
    fruit_list = ['apple', 'orange', 'mango']
    random.choice(fruit_list)
    

    这将从fruit_list中随机选择一个元素 如果您想从这三个列表中选择一个随机列表,则可以将这些列表放入如下列表中:-

    import random
    fruit_list = ['apple', 'orange', 'mango']
    transport_list = ['car', 'bus', 'ship']
    animal_list = ['cat', 'dog', 'Tiger']
    random.choice(fruit_list, transport_list, animal_list)
    

    【讨论】:

      【解决方案3】:

      如果您想从列表中随机选择项目,请执行以下操作:

      import random
      
      fruit_list = ['apple', 'orange', 'mango']
      transport_list = ['car', 'bus', 'ship']
      animal_list = ['cat', 'dog', 'Tiger']
      
      fruit = random.choice(fruit_list)
      transport = random.choice(transport_list)
      animal = random.choice(animal_list)
      

      使用random 库。


      如果您想从三个列表中的任何一个中选择一个项目,请将它们加在一起,然后使用random.choice()。另一种方法是使用

      import random
      
      fruit_list = ['apple', 'orange', 'mango']
      transport_list = ['car', 'bus', 'ship']
      animal_list = ['cat', 'dog', 'Tiger']
      
      fruit = random.choice(fruit_list)
      transport = random.choice(transport_list)
      animal = random.choice(animal_list)
      
      random_list = [fruit, transport, animal]
      random_item = random.choice(random_list)
      

      【讨论】:

      • 我知道,我需要的是 3 个列表中的一项。我找到了一种方法,我从 3 个列表中创建了另一个列表,然后我再次运行随机函数来获取最终项目。有没有其他方法可以做到这一点?
      • @PythonPitch 添加另一条评论而不是编辑原文
      • 当我使用你的语法时,出现错误 TypeError:choice() 需要 2 个位置参数,但给出了 3 个
      • @PythonPitch 没关系,把它们加在一起就可以了。您也可以通过单击旁边的灰色复选标记来接受我的回答。
      猜你喜欢
      • 2017-03-26
      • 1970-01-01
      • 2010-09-23
      • 2017-04-26
      • 1970-01-01
      • 1970-01-01
      • 2012-09-11
      • 1970-01-01
      相关资源
      最近更新 更多