Converting a list of list of strings to list of list of numbers

I have this list of string

[['1.1 1.2 1.3'], ['2.1 2.2 2.3'], ['3.1 3.2 3.3'], ['4.1 4.2 4.3']]

How can I convert it to

[[1.1,1.2,1.3], [2.1,2.2,2.3],[3.1,3.2,3.3], [4.1,4.2, 4.3]]
edit retag close merge delete

Sort by ยป oldest newest most voted

Let L denote your first list:

sage: L = [['1.1 1.2 1.3'], ['2.1 2.2 2.3'], ['3.1 3.2 3.3'], ['4.1 4.2 4.3']]

You can see that is is a list of lists where each second-level list has a single element that is a string.

sage: L[0][0]
'1.1 1.2 1.3'
sage: L[1][0]
'2.1 2.2 2.3'
sage: L[2][0]
'3.1 3.2 3.3'

Let us pick one as an example:

sage: s = L[0][0]
sage: s
'1.1 1.2 1.3'

This string is a concatenation of strings separated with space. We can split this long string into a list of shorter strings with respect to the space separator:

sage: s.split(' ')
['1.1', '1.2', '1.3']

We get a list of strings, each representing a floating-point number. Let us transform such stings into genuine floating-point numbers:

sage: [RDF(i) for i in s.split(' ')]
[1.1, 1.2, 1.3]

Putting everything together (i.e. iterating over all the elements of the list L that are lists with a single string in them), we get:

sage: [[RDF(i) for i in M[0].split(' ')] for M in L]
[[1.1, 1.2, 1.3], [2.1, 2.2, 2.3], [3.1, 3.2, 3.3], [4.1, 4.2, 4.3]]
more

Some variation:

[list(map(RDF,u[0].split())) for u in L]
( 2023-01-22 11:59:17 +0100 )edit

Another one:

[[RDF(j) for j in i.split()] for i in flatten(L)]
( 2023-01-22 17:32:57 +0100 )edit