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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With