I'm trying to learn python through HackerRank, and I've been stuck on reading stdin. The problem gives an array of integers as a single line of text formatted like:
1 2 3 4 5
This should become the array:
[1,2,3,4,5].
Since there are spaces in between the numerals in the input, how can I get to an array? I've tried split() and map(), but I kept getting errors or an array that still had spaces.
Thank you!
2 Answers 2
list(map(int, "1 2 3 4 5".split(" ")))
answered Dec 1, 2014 at 5:17
Amadan
200k23 gold badges253 silver badges321 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
bedna
>>> map(int, "1 2 3 4 5".split(" ")) <map object at 0x7f4b2489bc90>
This list comprehension works equally well on Python2 and Python3
[int(x) for x in "1 2 3 4 5".split()]
str.split() when given no parameters will split on any whitespace
answered Dec 1, 2014 at 5:27
John La Rooy
306k54 gold badges378 silver badges514 bronze badges
Comments
lang-py
splitdoesn't work? What made you think thatmapwould work? A particular error you're getting? That kind of stuff...list(map(int, "1 2 3 4 5".split()))