[英]How can I convert a list of strings into numeric values?
如何将字符串列表(每个字符串代表一个数字,即['1', '2', '3']
)转换为数值。
Use int()
and a list comprehensions : 使用
int()
和列表推导 :
>>> i = ['1', '2', '3']
>>> [int(k) for k in i]
[1, 2, 3]
As Long as the strings are of the form '1' rather than 'one' then you can use the int() function. 只要字符串的格式为“ 1”而不是“ one”,就可以使用int()函数。
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. 这两个示例都遍历字符串列表,并将int()函数应用于该值。
Try this method: 试试这个方法:
>>> int('5')
5
像这样:
map(int, ['1', '2', '3'])
a=['1','2','3']
map(lambda x: int(x),a)
> [1, 2, 3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.