开发者

Reading from a text file python

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
开发者_C百科

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.


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 = ....


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


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]


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜