(2, 9, 10, 12, 20, 31)这个为一组数据,很多种这个数据怎么保存起来然后随机取出5组
时间: 2023-10-26 13:35:43 浏览: 78
假设要保存多组数据,可以使用列表(list)的嵌套,每个内层列表代表一组数据,外层列表则保存所有的数据组,如下所示:
```python
data = [
[2, 9, 10, 12, 20, 31],
[3, 8, 11, 13, 19, 30],
[1, 7, 14, 15, 21, 32],
[4, 6, 16, 18, 22, 33],
[5, 17, 23, 24, 27, 34],
[25, 26, 28, 29, 35, 36]
]
```
要随机取出5组数据,可以使用random模块中的sample()函数,该函数可以从一个序列中随机取出指定个数的元素,并且不会重复。代码如下所示:
```python
import random
data = [
[2, 9, 10, 12, 20, 31],
[3, 8, 11, 13, 19, 30],
[1, 7, 14, 15, 21, 32],
[4, 6, 16, 18, 22, 33],
[5, 17, 23, 24, 27, 34],
[25, 26, 28, 29, 35, 36]
]
n = 5
samples = random.sample(data, n)
print(samples)
```
运行结果可能会类似于:
```
[[2, 9, 10, 12, 20, 31], [4, 6, 16, 18, 22, 33], [1, 7, 14, 15, 21, 32], [3, 8, 11, 13, 19, 30], [5, 17, 23, 24, 27, 34]]
```
注意:每次运行结果可能都不同,因为是随机选取的。
阅读全文