[英]convert a list of strings to a list of numbers?
I would like to convert a list of following strings into integers: 我想将以下字符串列表转换为整数:
>>> tokens
['2', '6']
>>> int(tokens)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string or a number, not 'list'
Other than writing a for loop to convert each member of the list tokens
, is there a better way to do that? 除了编写for循环以转换列表
tokens
每个成员之外,还有更好的方法吗? Thanks! 谢谢!
Just use list comprehension: 只需使用列表理解:
[int(t) for t in tokens]
Alternatively map
the int
over the list 或者将
int
map
到列表中
map(int, tokens)
However map
is changed in python3, so it creates an instance of the map and you would have to cast that back into a list if you want the list. 但是
map
在python3中已更改,因此它创建了map的实例,并且如果需要列表,则必须将其强制转换回列表。
i = iter(list)
while i.next != None:
print int(i.next())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.