convert string to number list with python
1. problem
How to convert a string like “1,2,3” or “{1,2,3}” to a number list, like [1,2,3]?
2. solution
step 1:
First of all, we need to find all number in the string. Actually, some of them are integers, and some are floats. So maybe regex is a good solution to find them, and the built-in library ‘re’ could help us.
code:1
2
3In[1]: re.findall(r'\d+\.?\d*', '1.2,3,..,,345')
Out[1]:
['1.2', '3', '345']
step 2:
we have got a list. Next, we just need to convert the item from a string to a number. There are two solutions to solve it here.
solution 1,
Firstly, I must tell you that the built-in class float could convert “3” to 3.0, but int could not covert “3.0” to 3. If you use the class int, you will get an error message blew.
with int:1
2
3
4
5In[1]: [int(i) for i in list_a]
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 1, in <listcomp>
ValueError: invalid literal for int() with base 10: '1.2'
with float: (the right way!)1
2
3
4In[1]: list_a = re.findall(r'\d+\.?\d*', '1.2,3,..,,345')
In[2]: [float(i) for i in list_a]
Out[2]:
[1.2, 3.0, 345.0]
solution 2,
Actually, I prefer this solution rather than the solution 1. We could use the built-in class list and function map to convert it. Here we also cannot covert string to int except that all of them are integers.
with list and map():1
2
3In[1]: list(map(float, list_a))
Out[1]:
[1.2, 3.0, 345.0]
3. reference
[1] https://stackoverflow.com/questions/7368789/convert-all-strings-in-a-list-to-int
[2] https://blog.csdn.net/u010412858/article/details/83062200