将targets.tolist()生成的列表保留两位小数
时间: 2023-12-14 16:39:06 浏览: 34
可以使用列表推导式和 round() 函数来实现保留两位小数的操作,具体代码如下:
```
new_targets = [round(num, 2) for num in targets.tolist()]
```
这里假设 targets 是一个 Numpy 数组或张量,通过调用 tolist() 方法将其转化为 Python 列表。然后,列表推导式遍历列表中的每个数值,调用 round() 函数将其保留两位小数,并将结果存储在新列表 new_targets 中。
相关问题
强制targets.tolist()生成的列表中元素有两位小数
可以使用 Python 的内置 round() 函数来实现:
```python
targets = torch.tensor([1.2345, 2.3456, 3.4567])
targets_list = [round(t.item(), 2) for t in targets]
print(targets_list)
```
输出结果为:
```
[1.23, 2.35, 3.46]
```
其中 round() 函数的第一个参数是要保留小数位数的数字,第二个参数是保留的小数位数。在上面的例子中,我们将每个数字保留了两位小数,并将其转换为 Python 的列表。
怎么将这里的元素变成数字["{:.2f}".format(num) for num in targets.tolist()]
你可以使用列表推导式来将其转换为数字。具体来说,你可以使用以下代码将列表中的每个元素转换为保留两位小数的浮点数:
```python
targets = [1.2345, 2.3456, 3.4567]
targets_formatted = [float("{:.2f}".format(num)) for num in targets]
print(targets_formatted)
```
输出结果:
```
[1.23, 2.35, 3.46]
```
在这里,`"{:.2f}".format(num)` 表示将 `num` 格式化为保留两位小数的字符串,`float()` 将这个字符串转换为浮点数。列表推导式则遍历原始的 `targets` 列表中的每个元素,并将其转换为保留两位小数的浮点数。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)