Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从列表中生成5个数字?_Python_Random_Python 3.x - Fatal编程技术网

Python 如何从列表中生成5个数字?

Python 如何从列表中生成5个数字?,python,random,python-3.x,Python,Random,Python 3.x,我正试图从一个列表中生成5个数字,但我不知道该怎么做? 我知道如何在随机模块中使用选择,但我希望它从如下列表中选择多个整数: randomnumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 或者我必须手动操作,例如: num1 = choice(randomnumbers) num2 = choice(randomnumbers) 等等 任何帮助都将不胜感激请使用: 这将从输入列表中选择5个不同的数字 如果允许重复编号,列表理解将使用random。选择可以: f

我正试图从一个列表中生成5个数字,但我不知道该怎么做? 我知道如何在随机模块中使用选择,但我希望它从如下列表中选择多个整数:

randomnumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
或者我必须手动操作,例如:

num1 = choice(randomnumbers)
num2 = choice(randomnumbers)
等等

任何帮助都将不胜感激

请使用:

这将从输入列表中选择5个不同的数字

如果允许重复编号,列表理解将使用
random。选择
可以:

from random import choice
picked = [choice(randomnumbers) for _ in range(5)]
演示:

>>> from random import sample, choice
>>> sample(randomnumbers, 5)
[1, 0, 9, 3, 2]
>>> [choice(randomnumbers) for _ in range(5)]
[1, 6, 5, 5, 0]
使用:

这将从输入列表中选择5个不同的数字

如果允许重复编号,列表理解将使用
random。选择
可以:

from random import choice
picked = [choice(randomnumbers) for _ in range(5)]
演示:

>>> from random import sample, choice
>>> sample(randomnumbers, 5)
[1, 0, 9, 3, 2]
>>> [choice(randomnumbers) for _ in range(5)]
[1, 6, 5, 5, 0]

是否允许重复选择,或者您希望列表中有五个不同的数字?是否允许重复选择,或者您希望列表中有五个不同的数字?