使用Python将列表中特定列转换为浮点数

-2 投票
1 回答
2072 浏览
提问于 2025-04-18 12:20

我有一个这样的列表:

[['1', '6', '192.168.4.118', '1605', '', '115.85.145.5', '80', '', '60', '0.000000000', '0x0010', 'Jun 15, 2010 18:27:57.490835000', '0.000000000'], 

['2', '6','115.85.145.5', '80', '', '192.168.4.118', '1605', '', '1514', '0.002365000', '0x0010', 'Jun 15, 2010 18:27:57.493200000', '0.002365000'], 

['3', '6', '115.85.145.5', '80', '', '192.168.4.118', '1605', '', '1514', '0.003513000', '0x0018', 'Jun 15, 2010 18:27:57.496713000', '0.005878000']]

我想把某一列转换成浮点数,但遇到了错误(比如说第四列)。

我试过这个代码:

for x in data:
    try:
        yield float(x)
    except ValueError:
        yield x

结果我得到了这个错误:

File "read csv file.py", line 17
  except ValueError:
                     ^
IndentationError: unindent does not match any outer indentation level

或者当我使用这个简单的代码时:

float (data [:][3])

想要只转换第三列(也就是第四列),也出现了错误。

请给我建议一个方法,让我可以把所有数据存储在一个变量里,这个变量可以同时包含浮点数和字符串。

1 个回答

1

在按照上面的建议修复了缩进错误之后;

转换单独的一列

data = [['1', '6', '192.168.4.118', '1605', '', '115.85.145.5', '80', '',
         '60', '0.000000000', '0x0010', 'Jun 15, 2010 18:27:57.490835000', '0.000000000'],
        ['2', '6','115.85.145.5', '80', '', '192.168.4.118', '1605', '', '1514',
         '0.002365000', '0x0010', 'Jun 15, 2010 18:27:57.493200000', '0.002365000'],
        ['3', '6', '115.85.145.5', '80', '', '192.168.4.118', '1605', '', '1514',
         '0.003513000', '0x0018', 'Jun 15, 2010 18:27:57.496713000', '0.005878000']]

for thing in data:
    thing[3] = float(thing[3])

将所有的 数字 转换为浮点数

def convert(sequence):
    for item in sequence:
        try:
            yield float(item)
        except ValueError as e:
            yield item

new = [list(convert(sublist)) for sublist in data]
# or
new = [[item for item in convert(sublist)] for sublist in data]

撰写回答