【问题标题】:Pythonic way of creating a list of list of floats from text file从文本文件创建浮点列表列表的 Pythonic 方法
【发布时间】:2019-06-18 09:43:36
【问题描述】:

我正在逐行读取 csv_reader 并尝试转换同一行上的浮点字符串列表。目前,我有:

list([float(i) for i in map(list, csv_reader)])

这显然行不通。我将如何实现我想要的?我也希望这一切都在一条线上。

我需要两个map 函数吗?也许两个 Pythonic for 循环?

我正在处理的函数是:

def csv_input(filename):

    print(f'Currently reading the annotations from {filename}')

    try:
        csv_input_file = open(filename, 'rt')
    except FileNotFoundError:
        program_help()
        print("[Error] Input File not found")

    csv_reader = csv.reader(csv_input_file, delimiter=',')
    unfiltered_annots = list(float(i) for i in map(list, csv_reader))
    csv_input_file.close()

    return unfiltered_annots

我的 CSV 文件如下所示:

11, 11, 24, 24, 0.75
10, 11, 20, 20, 0.8
11, 9, 24, 24, 0.7
40, 42, 20, 20, 0.6

我得到的错误是:

Traceback (most recent call last):
  File "maximal_supression.py", line 124, in test_google_doc_example
    unfiltered_annots = csv_input('example_input.csv')
  File "maximal_supression.py", line 34, in csv_input
    unfiltered_annots = list(float(i) for i in map(list, csv_reader))
  File "maximal_supression.py", line 34, in <genexpr>
    unfiltered_annots = list(float(i) for i in map(list, csv_reader))
TypeError: float() argument must be a string or a number, not 'list'

【问题讨论】:

    标签: python list for-loop map-function


    【解决方案1】:

    您正在尝试将列表转换为浮点数。如果您想将列表元素转换为浮点数,您还应该在列表理解中遍历您的列表:

    unfiltered_annots = list([[float(i) for i in l] for l in map(list, csv_reader)])

    在我稍微转换的代码中(为简单起见):

    import csv
    
    csv_input_file = open('a.csv', 'rt')
    csv_reader = csv.reader(csv_input_file, delimiter=',')
    unfiltered_annots = list([[float(i) for i in l] for l in map(list, csv_reader)])
    csv_input_file.close()
    unfiltered_annots
    

    它返回列表列表:

    [[11.0, 11.0, 24.0, 24.0, 0.75],
     [10.0, 11.0, 20.0, 20.0, 0.8],
     [11.0, 9.0, 24.0, 24.0, 0.7],
     [40.0, 42.0, 20.0, 20.0, 0.6]]
    

    附:正如 @meowgoesthedog 所述,csv_reader 返回列表,因此您无需将列表映射到 csv_reader:

    unfiltered_annots = [list(map(float, l)) for l in csv_reader]

    【讨论】:

    • map(list, csv_reader) 是多余的,因为 CSV 阅读器将行作为列表生成
    • @meowgoesthedog 为什么效率低?
    • 可以简化为[[float(i) for i in l] for l in csv_reader][list(map(float, l)) for l in csv_reader]
    • 我觉得我最喜欢[list(map(float, l) for l in csv_reader]。你为什么不回答我的问题?
    • File "maximal_supression.py", line 34 unfiltered_annots = [list(map(float, l) for l in csv_reader] ^ SyntaxError: invalid syntax
    猜你喜欢
    • 2016-02-26
    • 2019-11-29
    • 2013-07-27
    • 2010-10-29
    • 2015-08-05
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多