tags:

views:

99

answers:

3

I am reading in a string of integers such as "3 ,2 ,6 " and want them in the list [3,2,6] as integers. This is easy to hack about, but what is the "pythonic" way of doing it?

+10  A: 
mylist = [int(x) for x in '3 ,2 ,6 '.split(',')]
Wayne Werner
I think you have it a bit backwards: `'3,2,6'.split(',')`
orangeoctopus
@orangeoctopus It works fine anyway, `int` discard surrounding whitespace
delnan
@orangeoctupus - Yeah, I edited it when I realized that. But apparently I'm quick like a fox so it doesn't show I've edited it (at least to me...) ;)
Wayne Werner
@Wayne, now people like delnan think I'm an idiot :(
orangeoctopus
@orangeoctopus, sorry, I'll be slower than a fox next time... :)
Wayne Werner
+1  A: 

While a custom solution will teach you about Python, for production code using the csv module is the best idea. Comma-separated data can become more complex than initially appears.

Eli Bendersky
I wonder how comma separated integers get any complex?
Anurag Uniyal
@Anurag: Who said they had to be integers? The OP only provided sample data...
katrielalex
@Anurag: "teach him to fish..." - ever heard that fable? It's what I'm trying to do here. Just parsing a string of commas is rarely *the* task one attempts to solve, behind this there are more complex requirements. If I'm wrong, no harm done, other answers provide the simpler approach
Eli Bendersky
@katrielalex, the OP said, "I'm reading in a string of integers...". For a robust solution it's better to use the csv module as Eli recommends, of course.
Wayne Werner
Oops :$. Thanks.
katrielalex
@Eli, i have heard that fable, but sometimes for a very specific problems, we need not use complex solutions, like using csv module to read a list of integers
Anurag Uniyal
+10  A: 
map( int, myString.split(',') )
wheaties
+1 for being functional style
Matt Williamson
@Matt: actually, while personally I love the functional style, list comprehensions are more Pythonic
Eli Bendersky
@Eli, agree 100%
Matt Williamson