1

I have a text file which contains a matrix of numbers:

999 999 10 8 3 4 999 999 999 6 999 2 7 999 999 6 3 5 6 999 9 1 10 999 10 6 999 2 2 999 

I'm trying to read each line and store it into an array in Python but I'm having trouble changing each value into an int from a string. I tried using the int() when parsing each line but I get the error of not being able to pass list into the int() argument.

1
  • 2
    add sample of your code. Commented May 31, 2011 at 2:46

4 Answers 4

3

try that:

matrix = [[int(i) for i in line.split()] for line in open('myfile.txt')] 

[edit] if you don't want the first line just read it before.

with open('myfile') as f: f.readline() matrix = .... 
Sign up to request clarification or add additional context in comments.

2 Comments

Yes this seems to work good, but I forogot to mention i dont want to be reading the first line of the txt file, any ideas?
@JJc, please accept whatever answer was useful... you may accept by clicking the outlined grey check mark just below the answer voting arrows
2

Using map() to get a list of lists:

>>> with open('myfile.txt') as matrix: ... [map(int, line.split()) for line in matrix] ... [[999, 999, 10, 8], [3, 4, 999, 999, 999], [6, 999, 2, 7, 999], [999, 6, 3, 5, 6], [999, 9, 1, 10, 999], [10, 6, 999, 2, 2, 999]] 

2 Comments

why map inside a list comprehension if map does the same thing as [f(x) for x in iterable]?
@JBernardo, map() eliminates the inner for loop you are using inside your answer
0

For each line, split on space character, and then convert each token to an int. One way to do this, using list comprehension, is:

s = "999 999 10 8" [int(t) for t in s.split(" ")] #evaluates to [999, 999, 10, 8] 

1 Comment

split splits on whitespace per default
-1
nums = [] with open('file.txt') as f: for line in f: nums.append([int(n) for n in line.split()]) 

You could write that as one list comprehension, but that could get nasty.

3 Comments

Why could a list comprehension get nasty?
@Mike see the other answer. Nested list comprehensions are rarely good form; the one above might be the most concise but it's way too long and dense.
list comprehensions are fast and less verbose. CPython's gc closes the file if opened inside a comprehension.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.