从带有列表的6个变量中选择随机项的最简单方法是什么

时间:2017-10-20 19:30:50

标签: python variables

使我的问题更加简单 我想从这6个列表中选择1个随机项目 因此是一个随机数,包括列表中的所有项目。由于需要额外的代码,我不想把它们放在一长列表中

items_1 = ["soap","ketchup","pineapple","crisp","twix"]
items_2  = ["olives","mouse pad","shampoo","coke","ruler","pen"]
items_3 =  ["honey","mirror","chocolate bar","fanta"]
items_4 = ["candle","doughnuts","pencil","dr pepper","broccoli","cabbage"]
items_5 = ["book","butter","jam","umbrella","toolbox","knife"]
items_6 = [ "tissue","iphone case","jewels","sprite"]

2 个答案:

答案 0 :(得分:2)

您可以将列表存储在列表中,然后再拨打random.choice两次:

>>> import random
>>> items_1 = ["soap","ketchup","pineapple","crisp","twix"]
>>> items_2  = ["olives","mouse pad","shampoo","coke","ruler","pen"]
>>> items_3 =  ["honey","mirror","chocolate bar","fanta"]
>>> items_4 = ["candle","doughnuts","pencil","dr pepper","broccoli","cabbage"]
>>> items_5 = ["book","butter","jam","umbrella","toolbox","knife"]
>>> items_6 = [ "tissue","iphone case","jewels","sprite"]
>>> list_of_lists = [items_1, items_2, items_3, items_4, items_5, items_6]
>>> random.choice(random.choice(list_of_lists))
'toolbox'
>>> random.choice(random.choice(list_of_lists))
'mirror'

内部调用随机选择一个列表,外部调用随机选择一个元素。

或者,您可以将所有列表连接到单个列表,然后再调用randon.choice一次,但可以安全地假设它的性能稍差。

答案 1 :(得分:0)

import random
n = random.randint(0, 2)
n1= random.randint(0,2)
item1 = ["blue", "yellow", "brown"]
item2 = ["1", "2", "3"]
v = (item1, item2)
print(v[n][n1])

希望帮助