Python: How do I convert an array of strings to an array of numbers? [duplicate]
Possible Duplicate:
What is the easiest way to convert list with str into list with int? 开发者_如何学运维
current array: ['1','-1','1']
desired array: [1,-1,1]
Use int
which converts a string to an int, inside a list comprehension, like this:
desired_array = [int(numeric_string) for numeric_string in current_array]
List comprehensions are the way to go (see @sepp2k's answer). Possible alternative with map
:
list(map(int, ['1','-1','1']))
Let's see if I remember python
list = ['1' , '2', '3']
list2 = []
for i in range(len(list)):
t = int(list[i])
list2.append(t)
print list2
edit: looks like the other responses work out better
精彩评论