【问题标题】:converting lots of string lists to floats将大量字符串列表转换为浮点数
【发布时间】:2018-07-18 08:50:02
【问题描述】:

我找到了in this question 如何将字符串列表转换为浮点数:

list_of_floats = list(map(lambda x: float(x.replace(",", "")), list_of_string_floats))

我实际上有 12 个列表要转换:

U_mag = list(map(lambda x: float(x.replace(",", "")), U_mag))
B_mag = list(.........................................B_mag))

等等

一些列表包含像 '-999.000' 这样的项目,我想将其转换为浮点数,而其他列表则包含像 'act''QSO' 这样的项目,它们将保留为字符串。当然,我可以将上面相同的行写 12 次!

我试过了

for item in (U_mag, B_mag, V_mag, R_mag, K_mag, W1_mag,
          W2_mag, W3_mag, W4_mag, L_UV, Q, flag_uv):
    try:
        item = list(map(lambda x: float(x.replace(",", "")), item))
    except:
        pass

这不会引发任何错误,但不会按预期更改列表。肯定有比写 12 次相同的代码更好的方法。

我哪里错了?

【问题讨论】:

    标签: python-3.x list type-conversion


    【解决方案1】:

    通过为列表分配新列表,您将失去对要替换的原始列表的引用。

    所以而不是:

    item = list(map(lambda x: float(x.replace(",", "")), item))
    

    您应该将新列表分配给临时变量,如果它没有引发异常,请清除原始列表并使用临时列表扩展它,以免丢失原始引用:

    temp = list(map(lambda x: float(x.replace(",", "")), item))
    item.clear()
    item.extend(temp)
    

    【讨论】:

      猜你喜欢
      • 2011-11-25
      • 1970-01-01
      • 1970-01-01
      • 2019-10-31
      • 2017-09-26
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多