Ask Your Question
0

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

asked 2023-01-21 12:18:09 +0100

Cyrille gravatar image

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 flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-01-21 13:32:26 +0100

tmonteil gravatar image

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]]
edit flag offensive delete link more

Comments

Some variation:

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

Another one:

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

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2023-01-21 12:18:09 +0100

Seen: 353 times

Last updated: Jan 21 '23