5

Say I have a list like this:

a = ['hello','1','hi',2,'something','3'] 

I want to convert the numbers in the list into float while keeping the strings.

I wrote this:

for i in a:
    try:
        i = float(i)
    except ValueError:
        pass

Is there a more efficient and neat way to do this?

1
  • 5
    Are the numbers always in the same locations? Commented Oct 19, 2012 at 6:32

5 Answers 5

4

Based on what you've already tried:

a = ['hello', '1.0', 'hi', 2, 'blah blah', '3']

def float_or_string(item):
    try:
        return float(item)
    except ValueError:
        return item


a = map(float_or_string, mylist)

Should do the trick. I'd say that a try:... except:... block is both a) efficient and b) neat. As halex pointed out, map() does not change the list in place, it returns a new list, and you set a equal to it.

Sign up to request clarification or add additional context in comments.

Comments

1

You're changing the value of the variable i -> The content of the array a does not change! If you want to change the values in the array, you should rather implement it like this:

for index, value in enumerate(a):
    try :
        a[index] = float(value)
    except ValueError :
        pass

Comments

1

The try/except way is the Pythonic way of doing it, but if you really hate it, see if this serves your purpose:

a = ['hello','1','hi',2,'something','3']  

pattern = re.compile(r'^(-?\d+)(\.\d+)?') 

b = [float(item) if isinstance(item, str) and re.match(pattern, item) 
else item for item in a] 

2 Comments

Regex? Seems kind of like killing cockroaches with a shotgun :)
@JoelCornett Haha, I thought the OP does not like the try/except way of doing this, so maybe re is better for him.
0

What's about my short example:

a = ['hello','1','hi',2,'something','3']

for i, item in enumerate(a):
    if str(item).isdigit():
        a[i] = float(item)

print a

1 Comment

It would break on "1.0". Not sure if OP plans on having any of those, though.
0

I think this is short and better way :

a = ['hello','1','hi',2,'something','3']

for index,value in enumerate(a):

     if isinstance(value,int):

             a[index] = float(value)

print a

OUTPUT IS:['hello', '1', 'hi', 2.0, 'something', '3']

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.