Python选择列表,然后从获胜列表选择一项。

2024-04-24 08:17:42 发布

您现在位置: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

Tags: andimport列表outputrandom语句butsay
3条回答

让我们假设有东西可以给abl赋值,然后关注您感兴趣的位。你已经猜到了,要从列表x中获得一个随机项,你可以使用random.choice(x)。最后一步,选择了一个随机列表,是从中选择一个随机项。在代码中:

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

在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

或者是名单上的其他随机字母! 这是你想做的吗?你知道吗

把你的单子放到另一个单子上。获取一个介于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)

相关问题 更多 >