随机生成一个10行5列的二维列表,用列表推导式实现转置。要求每个元素的值范围在10~30之间。
时间: 2024-05-14 12:16:37 浏览: 90
【java毕业设计】网页时装购物系统源码(springboot+vue+mysql+说明文档+LW).zip
好的,我会回答你的第一个问题。以下是实现方法:
```
import random
# 随机生成二维列表
lst = [[random.randint(10, 30) for j in range(5)] for i in range(10)]
print('原始二维列表:')
print(lst)
# 列表推导式实现转置
new_lst = [[row[i] for row in lst] for i in range(len(lst[0]))]
print('转置后的二维列表:')
print(new_lst)
```
输出结果如下:
```
原始二维列表:
[[17, 23, 29, 25, 14], [29, 15, 10, 22, 18], [24, 25, 15, 11, 18], [30, 22, 25, 15, 19], [27, 26, 26, 10, 30], [19, 21, 11, 11, 24], [26, 11, 19, 11, 24], [29, 27, 10, 21, 22], [21, 27, 30, 19, 17], [19, 24, 19, 15, 19]]
转置后的二维列表:
[[17, 29, 24, 30, 27, 19, 26, 29, 21, 19], [23, 15, 25, 22, 26, 21, 11, 27, 27, 24], [29, 10, 15, 25, 26, 11, 19, 10, 30, 19], [25, 22, 11, 15, 10, 11, 11, 21, 19, 15], [14, 18, 18, 19, 30, 24, 24, 22, 17, 19]]
```
注:以上代码是 Python 3 语言编写的。
阅读全文