matovitch
matovitch

Reputation: 1284

How to parse a list of list of floats in python?

I am fairly new to python and I got a C program which can output a list of floats like this one :

f11
f12
...
f1n

f21
f22
...
f2m

.
.
.
fk1
...
fkl

I would like to get these floats into a list of list :

[[f11,...], [f21, ...], ..., [fk1,...]]

I have a solution (using a specific float as a delimiter) but it is quite ugly. The format of the input is flexible...Is there a simple solution ?

Upvotes: 0

Views: 84

Answers (1)

Michael0x2a
Michael0x2a

Reputation: 64118

Assuming your numbers look something like this:

1.435235
3.23421
4.523421
42.3241

-1.2342
0.09901
134134.2

1.2342111
13.111
14.23521

...where each group of numbers is separated by two newlines, you could have something like this:

def parse_group(group):
    return [float(n) for n in group.split('\n')]

def get_numbers(string, separator='\n\n'):
    groups = str.split(separator)
    return [parse_group(group) for group in groups]

Calling get_numbers on your function should yield something like:

>>> print get_numbers(input)
[[1.435235, 3.23421, 4.523421, 42.3241], [-1.2342, 0.09901, 134134.2], [1.2342111, 13.111, 14.23521]]

This assumes that each group is separated by two newline characters (a blank line), but you could parametrize it accordingly.

Upvotes: 2

Related Questions