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 个项目
谢谢你。
你的代码已经做了你想要它做的事情。它调用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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句