简体   繁体   中英

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 ax,y,z

my file is ax,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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM