1

Possible Duplicate:
Python: How do I convert an array of strings to an array of numbers?

I am trying to map a list of strings to Int, and when I map the Int function it is splitting 2 digit numbers into 2 item lists:

I have the following code:

>>> MyList
['10', '5', '6', '7', '8', '9']
>>> MyList = [map(int,x) for x in MyList]
>>> MyList
[[1, 0], [5], [6], [7], [8], [9]]

What is the correct way to get a list that looks like this:

[10, 5, 6, 7, 8, 9]
Community
  • 1
  • 1
Nick
  • 159
  • 1
  • 7

1 Answers1

9

Use map(int, ... directly on the list:

map(int, MyList)

or, in most circumstances, use a list comprehension:

[int(x) for x in MyList]

but not both.

map applies the function to every item in the iterable by itself -- that is its purpose.

Similarly, a list comprehension runs the expression on every item in the iterable, so you don't need map, just the expression you want to run every time.

agf
  • 171,228
  • 44
  • 289
  • 238
  • Also note that in python3.x, `map` returns an iterator, not a list. So in python2.x the 2 things above are equivalent whereas in python3.x there is a slight difference. – mgilson Apr 18 '12 at 00:35
  • @mgilson Good note, but we know in this case he's on Python 2 because of the code in his answer. – agf Apr 18 '12 at 00:38