将 n 列表中所有列表的元素转换为浮点数?

Convert elements of all lists in n-lists to floats?

我有一个列表的列表,看起来像这样:

[['1', '1', '13', '23', '1.0', '9', '20051102', '20170330', '16', '9', '2', '2', '24', '46', '7232.17'], ['2', '1', '13', '23', '1.0', '9', '20051102', '20170331', '28', '4', '5', '4', '19', '51', '6171.145'], ['3', '1', '13', '23', '1.0', '9', '20051102', '20170327', '8', '3', '0', '2', '15', '14', '4666.224'], ['4', '1', '13', '23', '1.0', '9', '20051102', '20170329', '22', '2', '1', '4', '18', '42', '5479.682'], ['5', '1', '13', '23', '1.0', '9', '20051102', '20170328', '15', '5', '6', '9', '28', '37', '9411.681'], ['6', '1', '3', '27', '0.0', '9', '20051228', '20170303', '6', '1', '0', '0', '14', '21', '3757.115'], ['7', '1', '3', '27', '0.0', '9', '20051228', '20170301', '1', '0', '1', '3', '40', '45', '10521.261'], ['8', '1', '3', '27', '0.0', '9', '20051228', '20170320', '2', '0', '0', '0', '174', '171', '43113.562'].

它是由以下代码创建的: lines = [[x for x in line.strip().split(',')] for line in myfile.readlines()[1:3000]]

现在,所有列表中的所有元素都是字符串,如果我尝试 lines = [[float(x) for x in line.strip().split(',')] for line in myfile.readlines()[1:3000]] 我收到一个错误。

问题是,如果我尝试类似的操作:

if str in lines: print(lines)

returns什么都没有。

我怀疑某些空字符串可能会导致问题,例如:['2976', '1', '1', '0', '', '4', '20160630', '20170318', '0', '0', '0', '0', '8', '2', '2125.364'] 第 4 个元素为空..

怎么办?

只需将您自己的函数写入 float 来处理空字符串:

def myFloat(str):
    if str:
       return float(str)
    return <your_default_value> #e.g -1

然后:

lines = [[myFloat(x) for x in line.strip().split(',')] for line in myfile.readlines()[1:3000]]

并且您始终可以创建没有空字符串的新列表,然后对其进行迭代。

更新:

仅当非空字符串时才使用 float(x),像这样:

lines = [[float(x) for x in line.strip().split(',') if x] for line in myfile.readlines()[1:3000]]

请注意最后的if x