1 Replies - 5130 Views - Last Post: 20 May 2009 - 12:47 PM Rate Topic: -----

#1 MCMLXXI  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 13-May 09

Python converting a txt file into multidimensional list

Posted 18 May 2009 - 04:57 PM

This is not so much a request for help, rather a request for comments.

I have written C/C++ code for many years but recently I took an interest in Python. I have been working through the problems at projecteuler.net and have started to get a good feel for the language (but still have to make a conscious effort not to put ;'s at the end of every line.)

Problem 81 requires reading a text file containing an 80x80 matrix. My code works file, but I have a feeling there is a much better and/or more elegant way of handling this part of the problem. Any comments from a more experienced Python coder would be greatly appreciated.

The relevant portion of the code:
infile = open('matrix.txt')
line = infile.readline()

y = []
for line in infile:
	a = 0
	b = 0
	x = []
	for it in line:
		b = b + 1
		if it == ',':
			x.append(int(line[a:b-1]))
			a = b
	x.append(int(line[a:]))
	y.append(x)

infile.close()



Thank you in advance.
MCMLXXI

Is This A Good Question/Topic? 0
  • +

Replies To: Python converting a txt file into multidimensional list

#2 MCMLXXI  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 13-May 09

Re: Python converting a txt file into multidimensional list

Posted 20 May 2009 - 12:47 PM

Answered my own question after a little bit of poking around and brushing off my regex skills.

import re

f1 = open('matrix.txt')

for lines in f1:
	matrix.append([int(v) for v in re.findall('\d\d?\d?\d?', lines)])

f1.close()



much sexier :D

MCMLXXI


View PostMCMLXXI, on 18 May, 2009 - 03:57 PM, said:

This is not so much a request for help, rather a request for comments.

I have written C/C++ code for many years but recently I took an interest in Python. I have been working through the problems at projecteuler.net and have started to get a good feel for the language (but still have to make a conscious effort not to put ;'s at the end of every line.)

Problem 81 requires reading a text file containing an 80x80 matrix. My code works file, but I have a feeling there is a much better and/or more elegant way of handling this part of the problem. Any comments from a more experienced Python coder would be greatly appreciated.

The relevant portion of the code:
infile = open('matrix.txt')
line = infile.readline()

y = []
for line in infile:
	a = 0
	b = 0
	x = []
	for it in line:
		b = b + 1
		if it == ',':
			x.append(int(line[a:b-1]))
			a = b
	x.append(int(line[a:]))
	y.append(x)

infile.close()



Thank you in advance.
MCMLXXI

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1