Efficiently create list of list of list with varying amount of input

Question:

I have a .txt file with floating point numbers inside. This file always contains an even number of values which need to be formatted as follows: [[[a,b],[c,d],[e,f]]]

The values always need to be in pairs of two. Even when there are less or more values: [[[a,b], ... [y,z]]]

So it needs to go from this:

3.31497114423 50.803721015, 7.09205325687 50.803721015, 7.09205325687 53.5104033474, 3.31497114423 53.5104033474, 3.31497114423 50.803721015

To this:

[[[3.31497114423,50.803721015],[7.09205325687,50.803721015],[7.09205325687,53.5104033474],[3.31497114423,53.5104033474],[3.31497114423,50.803721015]]]   

I have the feeling this can be done fairly easy and efficiĆ«nt. The code I have so far works, but is far from efficient…

with open(filename) as f:
    for line in f:
        footprint = line.strip()

    splitted = footprint.split(' ')
    list_str = []
    for coordinate in splitted:
        list_str.append(coordinate.replace(',', ''))

    list_floats = [float(x) for x in list_str]
    footprint = [list_floats[x:x+2] for x in range(0, len(list_floats), 2)]

    return [footprint]

Any help is greatly appreciated!

Asked By: Niek

||

Answers:

The split function is very useful in scenarios such as these.

with open(filename) as f:

    # Format the string of numbers into a list seperated by commas
    new_list = f.read().split(", ")

    # For every element in this list, make it a list seperated by space
    # Also convert the strings into floats
    for i in range(len(new_list)):
        new_list[i] = list(map(float, new_list[i].split(" ")))

    new_list = [new_list]

The first split converts the code from this

3.31497114423 50.803721015, 7.09205325687 50.803721015, 7.09205325687 53.5104033474, 3.31497114423 53.5104033474, 3.31497114423 50.803721015

To this

['3.31497114423 50.803721015', '7.09205325687 50.803721015', '7.09205325687 53.5104033474', '3.31497114423 53.5104033474', '3.31497114423 50.803721015']

The second split converts that to this

[['3.31497114423', '50.803721015'], ['7.09205325687', '50.803721015'], ['7.09205325687', 53.5104033474'], ['3.31497114423', '53.5104033474'], ['3.31497114423', '50.803721015']]

Then the mapping of the float function converts it to this (the list converts the map object to a list object)

[[3.31497114423, 50.803721015], [7.09205325687, 50.803721015], [7.09205325687, 53.5104033474], [3.31497114423, 53.5104033474], [3.31497114423, 50.803721015]]

The last brackets place the whole thing into another list

[[[3.31497114423, 50.803721015], [7.09205325687, 50.803721015], [7.09205325687, 53.5104033474], [3.31497114423, 53.5104033474], [3.31497114423, 50.803721015]]]
Answered By: Hhadley
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.