list转float
时间: 2023-08-07 18:08:43 浏览: 44
要列表中的字符串类型数据转换为浮点数类型,可以使用以下几种方法:
方法一:使用map函数和float函数将字符串列表转换为浮点数列表。可以参考以下代码:
```python
strList = ['222', '333', '444']
floatList = list(map(float, strList))
print(floatList)
```
输出结果为:[222.0, 333.0, 444.0]。[1]
方法二:使用循环遍历列表,并使用float函数将每个字符串元素转换为浮点数。可以参考以下代码:
```python
strList = ['222', '333', '444']
floatList = []
for num in strList:
floatList.append(float(num))
print(floatList)
```
输出结果为:[222.0, 333.0, 444.0]。[2]
方法三:如果字符串列表嵌套在另一个列表中,可以使用嵌套循环将所有字符串元素转换为浮点数。可以参考以下代码:
```python
dataset = [['222', '333', '444'], ['555', '666', '777']]
new_dataset = []
for sublist in dataset:
for num in sublist:
new_dataset.append(float(num))
print(new_dataset)
```
输出结果为:[222.0, 333.0, 444.0, 555.0, 666.0, 777.0]。[2]
以上是几种常见的将字符串列表转换为浮点数列表的方法,根据具体的需求选择适合的方法即可。