Gianni Spear
Gianni Spear

Reputation: 7936

Reading all lines in a file with list comprehension

I have a simple question and sorry if i post in stackoverflow. I am quite new in python and i don't remember how i can read in list compression a x,y,z

my file is a x,y,z file where each line is a points:

x1,y1,z1
x2,y2,z2
x3,y3,z3
........

inFile = "Myfile.las"

with lasfile.File(inFile, None, 'r') as f:
     # missing part
     points =[]

what i wish to save an object with only x and y

Thanks in advance and sorry for the simple question

Upvotes: 1

Views: 4081

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122392

You you wanted a list of x and y coordinates, it's easy enough:

with lasfile.File(inFile, None, 'r') as f:
     # missing part
     points = [line.split(',')[:2] for line in lasfile]

If these coordinates are integers, you can convert them to python int (from str) with a quick call to map():

points = [map(int, line.split(',')[:2]) for line in lasfile]

In python 3, where map is a generator, it's probably best to use a nested list comprehension:

points = [[int(i) for i in line.split(',')[:2]] for line in lasfile]

This'll result in a list of lists:

[[x1, y1], [x2, y2], ...]

Upvotes: 8

Related Questions