Home > Blockchain >  Elegant way to split a list of strings into nested lists with values of type float
Elegant way to split a list of strings into nested lists with values of type float

Time:09-17

Looking for an elegant way to split/format the below list of strings:

ls = ["12,45 58,96",
      "23,67 94,92 93,10",
      "45,76 33,11 46,33"] 

Goal is nested lists of x/y coordinates of type float:

goal = [[[12.0,45.0], [58.0,96.0]],
       [[23.0,67.0], [94.0,92.0], [93.0,10.0]]
       [[etc ......

I have solved this with the below code, but it's rough (and embarrassing!) and I know there has to be a much more elegant way, maybe using list comprehensions or generators?

s = []

for i in ls:
    i.split(' ')
    s.append(i)

res = [i.split(' ') for i in s] # splits at the space

gen = (map(lambda n: n.split(','), x) for x in res) # split list elements at comma
result = (list(x) for x in gen)

final = []

for i in result: # convert each string to a float
    sublist1 = []
    for x in i:
        sub = []
        for z in x:
            z = float(z)
            sub.append(z)
        sublist1.append(sub)
    final.append(sublist1)

print(list(final))

CodePudding user response:

You can try list comprehension like this -

newlist = [[[float(v) for v in e.split(',')] for e in st.split()] for st in l]

Output:

[[[12.0, 45.0], [58.0, 96.0]], [[23.0, 67.0], [94.0, 92.0], [93.0, 10.0]], [[45.0, 76.0], [33.0, 11.0], [46.0, 33.0]]]

CodePudding user response:

Using map

a = ["12,45 58,96", "23,67 94,92 93,10", "45,76 33,11 46,33"]
list(map(lambda x: list(map(lambda a: list(map(float, a.split(","))), x.split(" "))), a))
  • Related