2024-05-19 00:41:41 发布
网友
我有3个列表,每次我想随机挑选任何一个项目。我该怎么做
fruit_list = ['apple', 'orange', 'mango'] transport_list = ['car', 'bus', 'ship'] animal_list = ['cat', 'dog', 'Tiger']
如果要从列表中随机选择项目,请执行以下操作:
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
如果要从三个列表中选择一个项目,请将它们添加到一起,然后使用random.choice()。另一种方法是使用
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)
如果要从列表中随机选择项目,请执行以下操作:
使用
random
库如果要从三个列表中选择一个项目,请将它们添加到一起,然后使用
random.choice()
。另一种方法是使用您可以使用
random.choice()
将列表和组合列表中的样本添加到一起:
python中有一个名为random的模块。你可以用谷歌搜索它,但这里是你如何从列表中挑选随机元素的
这将从列表中选择一个随机元素 如果您想从这三个列表中随机选取一个列表,则可以将这些列表放入如下列表中:-
相关问题 更多 >
编程相关推荐