Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How do I convert an array of strings to an array of numbers? [duplicate]

Tags:

python

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]

like image 597
NullVoxPopuli Avatar asked Mar 15 '11 00:03

NullVoxPopuli


2 Answers

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] 
like image 60
sepp2k Avatar answered Sep 24 '22 14:09

sepp2k


List comprehensions are the way to go (see @sepp2k's answer). Possible alternative with map:

list(map(int, ['1','-1','1'])) 
like image 33
miku Avatar answered Sep 24 '22 14:09

miku