How can I convert a list of strings (each of which represents a number, i.e. [‘1’, ‘2’, ‘3’]
) into numeric values.
views:
210answers:
5It should pointed out that `map` is a built in function that applies the function `int` to every element of your list. Then returns a list of the results of that function.
Andrew Cox
2009-08-28 06:20:26
I keep forgeting that functional programming stuff like map exists, Thanks for reminding me of another nice way to modify lists.
Dan Goldsmith
2009-08-28 06:28:27
This is homework. Why provide a full answer? Why not provide hints, a direction and -- above all -- a reference to the int function?
S.Lott
2009-08-28 10:21:09
@S.Lott: It's been a while since I've had any homework. Man, what kind of school is that where the task is to look up a library function and have problems with doing it? BTW: I'll edit references to official docs.
Tadeusz A. Kadłubowski
2009-08-28 10:40:21
@Andrew: it returns list of results only in py2k, in py3k it returns a generator that needs to be converted into list explicitly.
SilentGhost
2009-08-28 11:01:08
+5
A:
As Long as the strings are of the form '1' rather than 'one' then you can use the int() function.
Some sample code would be
strList = ['1','2','3']
numList = [int(x) for x in strList]
Or without the list comprehension
strList = ['1','2','3']
numList = []
for x in strList:
numList.append(int(x))
Both examples iterate through the list on strings and apply the int() function to the value.
Dan Goldsmith
2009-08-28 06:15:31
+8
A:
Use int()
and a list comprehensions:
>>> i = ['1', '2', '3']
>>> [int(k) for k in i]
[1, 2, 3]
Swingley
2009-08-28 06:16:47