Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert list of string and number to string and float

Tags:

python

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?

like image 944
user1758399 Avatar asked Oct 19 '12 06:10

user1758399


People also ask

How do I convert a list of strings to list floats?

The most Pythonic way to convert a list of strings to a list of floats is to use the list comprehension floats = [float(x) for x in strings] . It iterates over all elements in the list and converts each list element x to a float value using the float(x) built-in function.

How do you convert a list of numbers to strings?

You can convert an integer list to a string list by using the expression list(map(str, a)) combining the list() with the map() function. The latter converts each integer element to a string.

How do you convert all elements to a float list?

Use a for-loop to convert all items in a list to floats. Use a for-loop and the syntax item in list to iterate throughout list . Use float(x) with item as x to convert item to type float . Append the converted item to a new list.


2 Answers

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.

like image 142
Joel Cornett Avatar answered Sep 30 '22 11:09

Joel Cornett


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
like image 31
gecco Avatar answered Sep 30 '22 09:09

gecco