如何将列表列表中的所有字符串转换为浮点数

时间:2016-12-28 14:35:17

标签: python excel python-2.7

我已经使用此代码打开excel文件,以创建excel文件的每一行列表:

import csv
with open("csvfile.csv", "rb") as f:
    lines = list(csv.reader(f))

>>> lines
[['0', '23.345', '-122.456'], ['1', '12.546', '-118.987'] ['2', '67.435', '-104.112']]

我确实希望将excel文件的每一行列表保存在一个更大的列表中,但我希望每个元素都是浮点数而不是字符串。我需要做些什么改变?

[[0, 23.345, -122.456], [1, 12.546, -118.987], [2, 67.435, -104.112]]

4 个答案:

答案 0 :(得分:3)

您可以在列表列表中使用嵌套的列表理解

>>> my_list = [['0', '23.345', '-122.456'], ['1', '12.546', '-118.987'], ['2', '67.435', '-104.112']]

>>> [[float(i) for i in sub_list] for sub_list in my_list]
[[0.0, 23.345, -122.456], [1.0, 12.546, -118.987], [2.0, 67.435, -104.112]]

答案 1 :(得分:1)

在阅读文件时,在列表理解中使用map

import csv

with open("csvfile.csv", "rb") as f:
    lines = [map(float, line) for line in csv.reader(f)]

保存两次创建列表(阅读,转换)

答案 2 :(得分:1)

您可以将map()list comprehension

一起使用
[map(float, sub_list) for sub_list in my_list]

<强>输出:

>>> [map(float, sub_list) for sub_list in my_list]
[[0.0, 23.345, -122.456], [1.0, 12.546, -118.987], [2.0, 67.435, -104.112]]

答案 3 :(得分:0)

变化:

lines = list(csv.reader(f))

成:

lines = [[float(x) for x in line] for line in csv.reader(f)]

即:

import csv
    with open("csvfile.csv", "rb") as f:
        lines =  [[float(x) for x in line] for line in csv.reader(f)]