如何将字符串列表转换为整数 - Python
我需要把一串字符串变成一串整数,我该怎么做呢?
比如说,把这些字符串:
('1', '1', '1', '1', '2')
转换成这些整数:
(1, 1, 1, 1, 2)。
4 个回答
2
使用 map
函数。
vals = ('1', '1', '1', '1', '2')
result = tuple(map(int, vals))
print result
输出结果:
(1, 1, 1, 1, 2)
这是和列表推导式的性能比较:
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')")
输出结果:
3.08675879197
4.08549801721
还有更长的列表:
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)
输出结果:
6.2849350965
7.36635214811
看起来,在我的电脑上,这种情况下,使用 map
的方法比列表推导式要快。
2
map(int, ls)
这里的 ls
是你字符串的列表。