Possible Duplicate:
开发者_如何学运维 How to convert strings into integers in python?
I need to change a list of strings into a list of integers how do i do this
i.e
('1', '1', '1', '1', '2') into (1,1,1,1,2).
Use list comprehensions:
strtuple = ('1', '1', '1', '1', '2')
intlist = [int(s) for s in strtuple]
Stuff for completeness:
As your “list” is in truth a tuple, i.e. a immutable list, you would have to use a generator expression together with a tuple constructor to get another tuple back:
inttuple = tuple(int(s) for s in strtuple)
The “generator expression” i talk about looks like this when not wrapped in a constructor call, and returns a generator this way.
intgenerator = (int(s) for s in strtuple)
map(int, ls)
Where ls
is your list of strings.
Use the map
function.
vals = ('1', '1', '1', '1', '2')
result = tuple(map(int, vals))
print result
Output:
(1, 1, 1, 1, 2)
A performance comparison with the list comprehension:
from timeit import timeit
print timeit("map(int, vals)", "vals = '1', '2', '3', '4'")
print timeit("[int(s) for s in strlist]", "strlist = ('1', '1', '1', '1', '2')")
Output:
3.08675879197
4.08549801721
And with longer lists:
print timeit("map(int, vals)", "vals = tuple(map(str, range(10000)))", number = 1000)
print timeit("[int(s) for s in strlist]", "strlist = tuple(map(str, range(10000)))", number = 1000)
Output:
6.2849350965
7.36635214811
It appears that, (on my machine) in this case, the map
approach is faster than the list comprehension.
You could use list comprehension which would look roughly like:
newList = [int(x) for x in oldList]
精彩评论