【问题标题】:Change a column string into int in Python’ list?在 Python 的列表中将列字符串转换为 int?
【发布时间】:2018-04-08 13:35:27
【问题描述】:

我有这样的数据:

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

谁能帮助我?谢谢!

【问题讨论】:

标签: python list


【解决方案1】:

展示方法

将字符串的某些列更改为 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']]

【讨论】:

  • 谢谢。很有帮助。
  • @song430 :当然。很高兴为您提供帮助
【解决方案2】:
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.']

【讨论】:

  • 太棒了!你的想法很有帮助!我会继续努力的。谢谢!!
  • regex和map(reduce filter)都是python中的强大工具
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-14
  • 1970-01-01
  • 2017-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多