Is there a way to directly convert the elements of a list taken from a split string?

Viewed 41

Let's say I have taken this line as input n='3.4 5.9 4.76 1.0'

I want to split it into a list and convert each element to a float. Here's how I would do that

nlist = n.split()
for i in range(nlist):
    nlist[i] = float(nlist[i])

This works fine but I was wondering, out of curiosity, if there was a way to save each element of the list as an actual number to avoid doing the second cycle and "manually" convert each element.

3 Answers

There are several ways to do this. You can map each item to a float then use list to convert the resulting map to a list:

nlist = list(map(float, n.split()))

You can do a list comprehension which is more Pythonic I think:

nlist = [float(i) for i in n.split()]

Edit: I just realized that you are trying to avoid second iteration. As Sayse mentioned in their answer if you really want to avoid second iteration, you will need to process your string character by character and create your own string. This is more costly than list comprehension so it's better to avoid doing something like that.

There is but it'd involve iterating over the characters of the string and building up a substring till you get to a space then casting that to a float. There isn't any other way to do this without iterating twice

curr_word = ""
floats = []
for c in n:
    if c == " ":
        floats.append(float(curr_word))
        curr_word = ""
        continue
    curr_word += c
if curr_word:
    floats.append(float(curr_word))

Its far more efficient to use your current approach or a list comprehension

Using Eval ## --> eval()

Eval will automatically convert the string to a Float Data type. Then how you iterate it, with a list comprehension, a function call or a for loop it doesn't really matter.

n='3.4 5.9 4.76 1.0'

nlist = [eval(n_) for n_ in n.split()]
for i in nlist:
    print(type(i))

Output

<class 'float'>
<class 'float'>
<class 'float'>
<class 'float'>

Using List comprehension

n='3.4 5.9 4.76 1.0'


nlist = [float(n_) for n_ in n.split()]
print(nlist)

Output

[3.4, 5.9, 4.76, 1.0]

Related