.用python语言生成一个6行12列的矩阵B,其元素值是小于或等于20的随机数
时间: 2023-05-31 20:06:05 浏览: 95
可以使用Python内置的random模块来生成随机数,然后使用嵌套循环来生成矩阵B。具体代码如下:
```python
import random
B = []
for i in range(6):
row = []
for j in range(12):
row.append(random.randint(1, 20))
B.append(row)
print(B)
```
输出结果类似于:
```
[[18, 10, 9, 17, 4, 16, 13, 18, 7, 2, 4, 4],
[4, 19, 17, 19, 1, 15, 17, 2, 1, 19, 13, 19],
[11, 4, 7, 2, 1, 17, 20, 10, 19, 4, 16, 1],
[10, 11, 11, 8, 17, 5, 7, 2, 6, 5, 3, 5],
[16, 5, 9, 17, 12, 16, 8, 18, 2, 3, 5, 15],
[5, 9, 17, 12, 12, 8, 13, 6, 13, 7, 20, 6]]
```
其中每个元素都是小于等于20的随机整数。
相关问题
用python语言生成一个6行12列的矩阵,其元素值是小于或等于20的随机数
```python
import random
matrix = [[random.randint(1, 20) for j in range(12)] for i in range(6)]
print(matrix)
```
输出:
```
[[7, 12, 14, 11, 15, 3, 1, 3, 7, 16, 17, 3],
[19, 7, 8, 18, 2, 18, 19, 20, 14, 9, 18, 15],
[8, 11, 16, 11, 12, 14, 4, 4, 4, 1, 4, 4],
[5, 11, 5, 10, 5, 2, 17, 7, 8, 14, 1, 3],
[7, 16, 6, 1, 3, 3, 19, 3, 7, 2, 6, 7],
[1, 9, 19, 15, 19, 10, 19, 6, 20, 11, 20, 10]]
```
. 生成一个6行12列的矩阵B,其元素值是小于或等于20的随机数。
以下是Python代码实现:
```python
import random
B = []
for i in range(6):
row = []
for j in range(12):
row.append(random.randint(1, 20))
B.append(row)
print(B)
```
输出结果类似如下:
```
[[4, 8, 2, 1, 9, 5, 8, 6, 7, 19, 4, 4],
[4, 9, 17, 1, 7, 8, 19, 3, 14, 2, 10, 6],
[3, 3, 2, 1, 12, 16, 11, 1, 7, 16, 11, 7],
[9, 11, 8, 1, 7, 10, 20, 16, 12, 3, 9, 3],
[2, 17, 14, 10, 16, 14, 15, 8, 9, 10, 15, 10],
[8, 1, 2, 10, 20, 6, 7, 2, 15, 6, 4, 5]]
```