![]() |
list of strings to list of float - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: list of strings to list of float (/thread-24516.html) |
list of strings to list of float - undoredo - Feb-17-2020 Hello, i am trying to read a text file to get a list of point coordinates from a texte file : this is the text : -48.9701217110874,5.67558617156734,0 -43.5855912406261,6.54875327488539,0 -51.1530394693826,-3.20161271216619,0 -45.6229811483682,-1.89186205718911,0 -37.0368379657407,5.23900261990832,0 -52.8993736760187,6.54875327488539,0 -56.5375699398439,-0.727639252765042,0 i called the file polyline.txt and this how i wrote the code : def ImportPointList(): f = open("polyline.txt") #open the text file lines = f.readlines() #read the line lines = [item.rstrip("\n") for item in lines] #divide the line in items pointList = list(lines) # create a list of items listLength = len(pointList) #tell me the number of items in the list print ("this is the new List",pointList,"composed of ",listLength,"items") The problem i have now is how to transform that list of strings into a list of float numbers How to remove the z coordinates since its 0 and if you are still interested by the problem ![]() the vector slope is (Yb-Ya)/(Xb-Xa) thanks !!!! RE: list of strings to list of float - michael1789 - Feb-17-2020 For each line item eg. -48.9701217110874,5.67558617156734,0 , you can use split() to turn it to a list. Then delete last item. Then use list comprehension to make a new list of floats. line_item = "-48.9701217110874,5.67558617156734,0" new_item = list(line_item.split(",")) del new_item[-1] coordinate = [float(num) for num in new_item] print(coordinate) print(type(coordinate[1])) RE: list of strings to list of float - scidam - Feb-17-2020 If this is not an assignment, I would recommend to use Pandas for such i/o operations. You can use pandas.read_csv function. This function automatically converts all values which look like float numbers to floats. Another option is to use Numpy (numpy.loadtxt) if you want to write your own function for reading this particular file, I wouldn't read the entire file at once ( f.readlines() ), but read it line-by-line, e.g. with open("polyline.txt") as f: result = [] for line in f: row = line.split(',')[:2] try: row = map(float, row) except ValueError: print("Couldn't convert row: %s " % row) else: result.append(list(row)) RE: list of strings to list of float - undoredo - Feb-19-2020 (Feb-17-2020, 11:40 PM)michael1789 Wrote: For each line item eg. I am sorry but i am new to python and programming. How would you write the loop that goes threw all the lines ? |