0

I am a python newbie.

I want to read a text file which reads something like this

1345..
245..
..456

and store it in a list of lists of integers. I want to keep the numbers and replaces the periods by 0s.How do i do it?

EDIT: Apologize for the ambiguous output spec

p.s I want the output to be a list of list

[ [1,3,4,5,0,0],
[2,4,5,0,0],
[0,0,4,5,6]]
1
  • 1
    I think just [0, 0, 4, 5, 6] for the last one... Commented Sep 25, 2012 at 6:28

3 Answers 3

4
with open('yourfile') as f:
    lst = [ map(int,x.replace('.','0')) for x in f ]

Which is the same thing as the following nested list-comp:

lst = [ [int(val) for val in line.replace('.','0')] for line in f]

Here I used str.replace to change the '.' to '0' before converting to an integer.

Sign up to request clarification or add additional context in comments.

2 Comments

as OP wants list of list : [ [int(x.replace('.','0'))] for x in f ]
@AshwiniChaudhary -- I'm not exactly sure that the OP means by "and store it in a list of lists as integers" ...
1
with open(file) as f:
   lis=[[int(y) for y in x.replace('.','0').strip()] for x in f]

Comments

0

Here's an answer in the form of classic for loops, which is easier for a newbie to understand:

a_list = []
l = []
with open('a') as f:
    for line in f:
        for c in line.rstrip('\n').replace('.', '0'):
            l.append(int(c))
        a_list.append(l)
        #next line
        l = []
print a_list

Comments

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.