开发者

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

This question already has answers here: Closed 10 years ago.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜