ash
ash

Reputation: 1200

Building a List from a text file in python

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

Upvotes: 0

Views: 80

Answers (3)

hyao
hyao

Reputation: 11

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

Upvotes: 0

mgilson
mgilson

Reputation: 309821

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.

Upvotes: 4

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250871

with open(file) as f:
   lis=[[int(y) for y in x.replace('.','0').strip()] for x in f]

Upvotes: 1

Related Questions