从文本fi创建浮动列表的Pythonic方法

2024-10-03 11:12:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我从一个csv\u阅读器中逐行读取,并试图转换同一行上的浮点字符串列表。目前,我有:

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'

Tags: csvinmapforinputfloatfilenamelist
1条回答
网友
1楼 · 发布于 2024-10-03 11:12:18

您正在尝试将列表转换为浮动。如果要将list的元素转换为float,还应在list中遍历列表:

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]]

另外,正如前面提到的,csv_reader返回列表,因此您不需要将列表映射到csv\u读取器:

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

相关问题 更多 >