Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a list of strings to ints (or doubles) in Python

I have a lots of list of strings that look similar to this:

list = ['4', '-5', '5.763', '6.423', '-5', '-6.77', '10']

I want to convert it to a list of ints (or doubles) but the - keeps producing an error.

like image 249
user1532369 Avatar asked Jul 30 '12 13:07

user1532369


People also ask

How do you convert multiple strings to integers in Python?

In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.

How do you convert strings to numeric in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .

How do you convert a string to a double in Python?

To convert a string with digits to a “double” (i.e., “float”) in Python, use the built-in function float(string) . For example, the expression float('123.456') will yield the float result 123.456 .

Can you convert strings to ints?

Use Integer.parseInt() to Convert a String to an Integer This method returns the string as a primitive type int.


1 Answers

>>> lst = ['4', '-5', '5.763', '6.423', '-5', '-6.77', '10']
>>> map(float, lst)
[4.0, -5.0, 5.763, 6.423, -5.0, -6.77, 10.0]

And don't use list as a variable name

like image 139
applicative_functor Avatar answered Sep 23 '22 02:09

applicative_functor