Converting a list of strings into a list of integers?
janpeterr at freenet.de
Sun Jul 22 18:20:18 CEST 2012
On 22.07.2012 18:39, Alister wrote:
> On Sun, 22 Jul 2012 10:29:44 -0500, Tony the Tiger wrote:
>> I came up with the following:
>> # options.modus_list contains, e.g., "[2,3,4]"
>> # (a string from the command line)
>> # MODUS_LIST contains, e.g., [2,4,8,16]
>> # (i.e., a list of integers)
>> if options.modus_list:
>> intTmp = 
>> modTmp = options.modus_list[1:-1]
>> for itm in modTmp:
>> MODUS_LIST = intTmp
> looks like a classic list comprehension to me and can be achieved in a
> single line
> MODUS_LIST=[int(x) for x in options.modus_list]
I am not sure why everyone is using the for-iterator option over a
"map", but I would do it like that:
MODUS_LIST= map(int, options.modus_list)
"map" works on a list and does commandX (here "int" conversion, use
"str" for string.. et cetera) on sequenceY, returning a sequence. More
in the help file.
And if I'm not completely mistaken, it's also the quicker way to do
performance wise. But I can't completely recall the exact reason.
More information about the Python-list