如何随机地从列表中选择项目

时间:2020-05-27 07:43:29

标签: python-3.x list random

 mal = ["a","b","c","d","e","f","g"]
num_to_select = randint(1,4)                
list_of_random_items = random.sample(mal , num_to_select)
first_random_item = list_of_random_items[0]
second_random_item = list_of_random_items[1] 
print(second_random_item)
print(first_random_item)

我在这里搜索了一些类似的问题,并尝试对答案进行一些编辑,但不起作用。

我想为随机时间选择随机项目,例如;

python随机选择数字4

随机打印列表中的4个项目

谢谢。

1 个答案:

答案 0 :(得分:0)

您的代码已经完成了您想要的工作。它调用random.randint以获得1到4之间的随机数。然后使用该随机数来使用random.sample检索该数量的项目。

random.sample返回一个list,其中包含它提取的所有值。因为您无法事先知道此列表的大小(最好是小),所以最好的选择是动态遍历该列表,并在其中打印值。

我已更改您的代码以在此处执行此操作:

import random

mal = ["a", "b", "c", "d", "e", "f", "g"]

num_to_select = random.randint(1, 4)
list_of_random_items = random.sample(mal, num_to_select)

for item in list_of_random_items:
    print(item)