I am reading data from a cvs file and when I import data into a list it will treat the numbers as strings.
This is the output: ['1.0', '1.20798878439', '1.52379907139']
but I want something like this [1.0, 1.20798878439, 1.52379907139]
so that I am dealing with real numbers and NOT strings? Any suggestions?
Asked
Active
Viewed 1,951 times
0

Micke redo
- 33
- 1
- 7
-
What you are trying to do is called `casting` or `type conversion`. Read more [here](https://en.wikipedia.org/wiki/Type_conversion) – kylieCatt Jun 08 '16 at 14:59
-
1Welcome to StackOverflow. A future pointer is if you have any question, basic or hard core - please include what you've tried thus far to solve it. As of now you question has zero proof of you putting in any effort in solving the problem yourself and it's well documented both on SO and in any search engine you could possibly imagine. In this case I posted a answer below so you can carry on with your programming but I've also marked this question as a duplicate. – Torxed Jun 08 '16 at 14:59
2 Answers
3
my_string_list = ['1.0', '1.20798878439', '1.52379907139']
my_int_list = [float(i) for i in my_string_list]
You'd simply iterate over it an convert it to the data type you need.
As pointed out by @IanAuld - This is called type casting or type conversion.
There are libraries that can handle trickier conversions for you.
But the bare essentials are a for
loop, iterate over each object in your list and convert it and finally place the result in a new list.
If i were to expand my answer from using list comprehensions
to a regular for loop, it would look like this:
my_string_list = ['1.0', '1.20798878439', '1.52379907139']
my_int_list = []
for item in my_string_list:
my_int_list.append(float(item))

Torxed
- 22,866
- 14
- 82
- 131
0
You can type cast and create a new list easily by using a list comprehension like so:
>>> [float(x) for x in ['1.0', '1.20798878439', '1.52379907139']]
[1.0, 1.20798878439, 1.52379907139]
Using variables:
>>> a = [1.0, 1.20798878439, 1.52379907139]
>>> b = [float(x) for x in a]
>>> print(b)
[1.0, 1.20798878439, 1.52379907139]
For more information on list comprehensions: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

HEADLESS_0NE
- 3,416
- 4
- 32
- 51