Converting a list of strings into a list of integers?

Jan Riechers janpeterr at freenet.de
Sun Jul 22 12:20:18 EDT 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:
>>              intTmp.append(int(itm))
>>          MODUS_LIST = intTmp
>>
>>
>> TIA
>>
>>
>>   /Grrr
>
> 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]
>
>
>

Hi,

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.

Jan



More information about the Python-list mailing list