如何从4个列表中随机选择一个列表?

2024-05-19 00:41:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: 项目apple列表carlistcattransporttiger
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)

您可以使用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))

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

import random
fruit_list = ['apple', 'orange', 'mango']
random.choice(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)

相关问题 更多 >

    热门问题