在Python'list中将一个列字符串改为int

2024-04-20 02:44:06 发布

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

我有这样的数据:

0,tcp,http,SF,181,5450,0.11,0.00,0.00,0.00,,normal.
0,tcp,http,SF,239,486,0.05,0.00,0.00,0.00,normal.
0,tcp,http,SF,235,1337,0.03,0.00,0.00,0.00,normal.
0,tcp,http,SF,219,1337,0.03,0.00,0.00,0.00,normal.

原始数据以txt格式存储。我使用list将它们存储在python中。但格式是字符串。然后我想把字符串的一些列改成int,如下所示:

^{pr2}$

有人能帮我吗?谢谢您!在


Tags: 数据字符串txthttp原始数据格式sflist
2条回答

展示如何

change some columns of string into int

list为例:

>>> l = [['1','2','3'], ['4','5','6'], ['7','8','9']]

#based on index from 0
>>> row_to_change = 1

>>> [ int(row[row_to_change]) for row in l ]
    [2, 5, 8]

现在,如果您想在list中更改它:

^{pr2}$
import re

fn = lambda i:float(i) if re.match('\d+(\.\d+)?',i) else i

with open('test.txt') as f:
    for line in f:
        line = list(map(fn,line.split(',')))
        print(line)



[0.0, 'tcp', 'http', 'SF', 181.0, 5450.0, 0.11, 0.0, 0.0, 0.0, '', 'normal.\n']
[0.0, 'tcp', 'http', 'SF', 239.0, 486.0, 0.05, 0.0, 0.0, 0.0, 'normal.\n']
[0.0, 'tcp', 'http', 'SF', 235.0, 1337.0, 0.03, 0.0, 0.0, 0.0, 'normal.\n']
[0.0, 'tcp', 'http', 'SF', 219.0, 1337.0, 0.03, 0.0, 0.0, 0.0, 'normal.']

相关问题 更多 >