在Python列表中将列字符串更改为int?

时间:2017-10-27 02:39:33

标签: python list

我有这样的数据:

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,如下所示:

'181' to 181

任何人都可以帮助我吗?谢谢!

2 个答案:

答案 0 :(得分:0)

展示如何

  

将某些字符串列更改为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本身更改它:

>>> for row in l :
        row[row_to_change] = int(row[row_to_change])

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

答案 1 :(得分:0)

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