优化以下代码# 去掉列表中的字符串,并将剩下的数字转换为浮点数 lst_num = [[float(i) for i in l.split() if i.replace('.', '', 1).isdigit()] for l in reports] # 将二维列表转换为 NumPy 数组,并沿着第一维求平均值 arr_mean = np.mean(np.array(lst_num), axis=0) # 将平均值数组转换回列表,并以原始表格的形式输出 lst_mean = [[''] + reports[0].split()[1:]] + [ ['{:.2f}'.format(n) if isinstance(n, float) else str(n) for n in arr_mean]] print(lst_mean)
时间: 2024-02-06 15:02:59 浏览: 89
C语言浮点数转字符串_C语言浮点数字符串_浮点数转换_
5星 · 资源好评率100%
可以进行如下优化:
1. 使用列表推导式和条件表达式过滤掉非数字字符串:
```
lst_num = [[float(i) for i in l.split() if i.replace('.', '', 1).isdigit()] for l in reports]
```
可以改写为:
```
lst_num = [[float(i) for i in l.split() if i.replace('.', '', 1).isdigit()] for l in reports if any(i.replace('.', '', 1).isdigit() for i in l.split())]
```
2. 使用 NumPy 的 loadtxt 函数将列表转换为数组:
```
arr_mean = np.mean(np.array(lst_num), axis=0)
```
可以改写为:
```
arr_mean = np.mean(np.loadtxt(lst_num), axis=0)
```
3. 使用列表推导式将平均值数组转换为列表:
```
lst_mean = [[''] + reports[0].split()[1:]] + [ ['{:.2f}'.format(n) if isinstance(n, float) else str(n) for n in arr_mean]]
```
可以改写为:
```
lst_mean = [[''] + reports[0].split()[1:]] + [['{:.2f}'.format(n) if isinstance(n, float) else str(n) for n in arr_mean]]
```
完整优化代码如下:
```
lst_num = [[float(i) for i in l.split() if i.replace('.', '', 1).isdigit()] for l in reports if any(i.replace('.', '', 1).isdigit() for i in l.split())]
arr_mean = np.mean(np.loadtxt(lst_num), axis=0)
lst_mean = [[''] + reports[0].split()[1:]] + [['{:.2f}'.format(n) if isinstance(n, float) else str(n) for n in arr_mean]]
print(lst_mean)
```
阅读全文