python选择列表,然后从获胜列表中选择一个项目

时间:2019-02-20 19:01:51

标签: python

尝试按照说明进行操作,让python随机选择一个列表,然后从“获胜”列表中选择一条语句并将其输出

类似:

import random

list1 = a, b, c, d
list2 = e, f, g, h
list3 = i, j, k, l
list4 = list1, list2,list3

output = random.choice(list4)
print(output)

but say list3 won and the output is k

3 个答案:

答案 0 :(得分:2)

在Python 3中,代码:

import random

list1 = ['a', 'b', 'c', 'd']
list2 = ['e', 'f', 'g', 'h']
list3 = ['i', 'j', 'k', 'l']
list4 = [list1, list2, list3]

winning_list = random.choice(list4)
output = random.choice(winning_list)
print(output)

给我:

  

“ >>> j

或列表中的其他随机字母! 这会像您要尝试的吗?

答案 1 :(得分:2)

让我们假设可以为ab,...,l赋值,并专注于您感兴趣的部分。到那里-您已经认为要从列表x中获得随机项目,可以使用random.choice(x)。选择了随机列表的最后一步是从中选择一个随机项目。在代码中:

output = random.choice(random.choice(list4))

答案 2 :(得分:0)

只需将您的列表放入另一个列表。获取介于0和列表长度之间的随机整数。减去1,因为您的列表以0开头。

from random import randint

list1 = a, b, c, d
list2 = e, f, g, h
list3 = i, j, k, l
list4 = list1, list2,list3
#get random list
list_of_lists = [list1, list2, list3, list4]
length_of_list = len(list_of_lists)
rand = randint(0, length_of_lists - 1)
randlist = list_of_lists[rand]
#Repeat to get random item
lenlist = len(randlist) #get length of list
rand = randint(0,lenlist -1)
random_item = randlist[rand]

print(random_item)
相关问题