3
\$\begingroup\$

I'm newbie in Python but I want to know some tricks to make my code look cute. I know that syntax of Python allows to do this, but I don't know how. Suppose I have file with lines of format "x y z" and I want to parse it and make some objects. Now code looks like this:

class Point(object):
 def __init__(self, x, y, z):
 self.x = x;
 self.y = y;
 self.z = z;
...
def load_file(file_path):
 points = [];
 with open(file_path, "r") as input_file:
 for line in input_file:
 str_point = line.split();
 x = float(str_point[0]);
 y = float(str_point[1]);
 z = float(str_point[2]);
 points.append(Point(x, y, z));
 return points;

Is there any way to make this code simpler?

asked Oct 20, 2014 at 9:17
\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

Instead of parsing x, y, z one by one, you can use a list comprehension, and pass the whole thing directly to the the constructor of Point using * like this:

def load_file(file_path):
 objects = []
 with open(file_path) as input_file:
 for line in input_file:
 obj = Point(*[float(x) for x in line.split()])
 objects.append(obj)
 return objects

I dropped the "r" in open(..., "r"), as that's the default anyway. Even more importantly, ; are not required to end statements in Python, and they are just noise in the posted code.

It would be even cuter to use a generator pattern instead:

def load_file(file_path):
 with open(file_path) as input_file:
 for line in input_file:
 yield Point(*[float(x) for x in line.split()])

You could iterate over this to do something with the objects, for example:

for obj in load_file(file_path):
 # do something ...

Or you could load all into a list using a list comprehension:

objects = [x for x in load_file(file_path)]
rolfl
98.1k17 gold badges219 silver badges419 bronze badges
answered Oct 20, 2014 at 9:30
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.