【问题标题】:How to convert values to float and assign them to a dictionary in Python?如何将值转换为浮点数并将它们分配给 Python 中的字典?
【发布时间】:2014-02-04 14:23:06
【问题描述】:

我正在尝试从 CSV 文件中读取内容并将它们存储在字典中。

我的 CSV 文件的每一行都格式化为:

'Node_001', '0.0067', '0.2456', '0.7896', ......

第一个元素将用作字典中的键,其余部分是值。

由于这些值是由 excel 中的方程式生成的,我认为格式本身没有任何问题。

这是我的代码:

with open(path, "rb") as file:
    reader = csv.reader(file)

    my_dictionary = dict()           

    for row in reader:
        node_id = row[0]
        temp_values = row[1:]
        [float(x) for x in temp_values]
        my_dictionary[node_id] = temp_values 
        print isinstance(temp_values[0], float)

我打印行的数字部分的第一个元素以检查它们是否转换为浮点数。但是,我得到的只是False

那么,我可以知道我的代码有什么问题吗?

谢谢。

【问题讨论】:

标签: python dictionary list-comprehension


【解决方案1】:

[float(x) for x in temp_values] 行不会修改 temp_values 而是创建一个新列表。你必须像这样重新分配它:

with open(path, "rb") as file:
reader = csv.reader(file)

my_dictionary = dict()           

for row in reader:
    node_id = row[0]
    temp_values = row[1:]
    temp_values = [float(x) for x in temp_values]
    my_dictionary[node_id] = temp_values 
    print isinstance(temp_values[0], float)

【讨论】:

    【解决方案2】:

    这段代码:

    for row in reader:
        node_id = row[0]
        temp_values = row[1:]
        [float(x) for x in temp_values]
        my_dictionary[node_id] = temp_values 
        print isinstance(temp_values[0], float)
    

    用这一行创建一个浮点值列表:

        [float(x) for x in temp_values]
    

    ...但由于它没有分配给任何东西,它立即消失。

    将该行更改为

        temp_values = [float(x) for x in temp_values]
    

    创建转换后的列表并将其分配给temp_values,以便您的其余代码可以使用这些值。

    【讨论】:

      【解决方案3】:

      假设您的文件中只有唯一键,请尝试此更改:

      with open(path, 'r') as f:
          reader = csv.reader(f)
          d = {r[0]:map(float, r[1:]) for r in reader}
      print(d)
      

      你也可以坚持使用列表推导:

      with open(path, 'r') as f:
          reader = csv.reader(f)
          d = {r[0]: [float(i) for i in r[1:]] for r in reader}
      

      【讨论】:

        【解决方案4】:

        您没有保存转换:

        temp_values = [float(x) for x in temp_values]
        

        如果你用这个替换你的列表理解,你的代码应该可以工作。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-10-12
          • 2018-01-23
          • 1970-01-01
          • 2021-05-13
          • 1970-01-01
          • 2014-05-28
          • 1970-01-01
          相关资源
          最近更新 更多