1

I have data like this:

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.

The original data was stored in txt. I used list to store them in python. But the format is string. Then I want to change some columns of string into int like this:

'181' to 181

Could anyone can help me? Thank you!

6

2 Answers 2

0

Showing how to

change some columns of string into int

with an example 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]

Now in case you want to change it in the list itself :

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

>>> l
[['1', 2, '3'], ['4', 5, '6'], ['7', 8, '9']]
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. It's helpful.
@song430 : sure. Glad to help
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.']

2 Comments

Great!Your idea is very helpful!I will work on the re. Thank you!!
regex and map(reduce filter) are both powerful tool in python

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.