Yankswin1
Yankswin1

Reputation: 35

Splitting strings within nested lists in Python and converting to float?

I am trying to split my nested list of strings into nested lists of floats. My nested list is below:

nested = [['0.3, 0.4, 0.2', '0.5, 0.1, 0.3'], ['0.7, 0.4, 0.2'], ['0.4, 0.1, 0.3']]

My desired output would be a nested list where these values remain in their sublist and are converted to floats as seen below:

nested = [[0.3, 0.4, 0.2, 0.5, 0.1, 0.3], [0.7, 0.4, 0.2], [0.4, 0.1, 0.3]]

The difficulty has come when trying to handle sublists with multiple strings (I.e. the first element). I have found some examples such as here How do I split strings within nested lists in Python?, but this code only handles sublists with one string element and I'm unsure how to apply this to sublists with multiple strings.

I am trying to avoid hardcoding anything as this is part of a script for a larger dataset and the sublist length may vary.

If anyone has any ideas, I'd appreciate some help.

Upvotes: 0

Views: 401

Answers (3)

Iuri Guilherme
Iuri Guilherme

Reputation: 461

nested = [['0.3, 0.4, 0.2', '0.5, 0.1, 0.3'], ['0.7, 0.4, 0.2'], ['0.4, 0.1, 0.3']]

new_nested = [[float(number) for strings in sublist for number in strings.split(', ')] for sublist in nested]

print(new_nested)

new_nested = list()

for sublist in nested:
  sublist_new_nested = list()
  for strings in sublist:
    for number in strings.split(', '):
      sublist_new_nested.append(float(number))
  new_nested.append(sublist_new_nested)

print(new_nested)

Output:

[[0.3, 0.4, 0.2, 0.5, 0.1, 0.3], [0.7, 0.4, 0.2], [0.4, 0.1, 0.3]]
[[0.3, 0.4, 0.2, 0.5, 0.1, 0.3], [0.7, 0.4, 0.2], [0.4, 0.1, 0.3]]

Upvotes: 0

Steven Rumbalski
Steven Rumbalski

Reputation: 45542

result = [[float(t) for s in sublist for t in s.split(', ')] for sublist in nested]

which is equivalent to

result = []
for sublist in nested:
    inner = []
    for s in sublist:
        for t in s.split(', '):
            inner.append(float(t))
    result.append(inner)

Upvotes: 3

Mark Bennett
Mark Bennett

Reputation: 1474

OK, starting with your example:

myNestedList = [['0.3, 0.4, 0.2', '0.5, 0.1, 0.3'], ['0.7, 0.4, 0.2'], ['0.4, 0.1, 0.3']]

myOutputList = []
for subList in myNestedList:
    tempList = []
    for valueStr in sublist:
        valueFloat = float( valueStr )
        tempList.append( valueFloat )
    myOutputList.append( tempList )

It will look something like that. (don't have time to try it out, but pretty close to correct)

Upvotes: 0

Related Questions