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

问题描述 投票:1回答:3

尝试按照说明进行操作,让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
python
3个回答
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

或列表列表中的其他随机字母!这会像你想做的那样吗?


2
投票

让我们假设有一些东西给ab,...,l赋予价值,并专注于你感兴趣的位。你大部分都在那里 - 你已经已经认识到从一个随机的项目列出x你可以使用random.choice(x)。选择随机列表的最后一步是从中选择一个随机项。在代码中:

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

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)
© www.soinside.com 2019 - 2024. All rights reserved.