Converting a list of strings into a list of integers?

Alister alister.ware at ntlworld.com
Sun Jul 22 17:39:54 CEST 2012


On Sun, 22 Jul 2012 10:29:44 -0500, Tony the Tiger wrote:

> Hi,
> Is there such a thing in the language, or do I have to invent it myself?
> 
> 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
> 
> There are probably never more than maybe between one to four items in
> the options.modus_list, and its contents as integers should always
> replace all of the original MODUS_LIST, because it is up to the user to
> decide what should be used for calculating the result.
> 
> The above works (unless I have introduced some bug when I copied into my
> editor here), but I would like to know if there already is such a thing,
> or something better than the above. I'd hate to re-invent the wheel.
> 
> 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]



-- 
NOTICE:

-- THE ELEVATORS WILL BE OUT OF ORDER TODAY --

(The nearest working elevator is in the building across the street.)



More information about the Python-list mailing list