python - Converting str numbers in list to int and find out the sum of the list -


i have list, numbers in strings can't find sum of list, need in converting numbers in list int.

this code

def convertstr(cals):     ret = float(cals) return ret totalcal = sum(cals) 

so there list called cals , looks this

 (20,45,...etc) 

but numbers in strings when try finding sum this

totalcal = sum(cals) 

and run shows error saying list needs int format question how convert numbers in list int format?

if have different way of finding sum of lists too.

you can use either python builtin map or list comprehension this

def convertstr(cals):     ret = [float(i) in (cals)]     return ret 

or

def convertstr(cals):     return map(float,cals) 

here timeit results both approaches

$ python -m timeit "cals = ['1','2','3','4'];[float(i) in (cals)]" 1000000 loops, best of 3: 0.804 usec per loop $ python -m timeit "cals = ['1','2','3','4'];map(float,cals)" 1000000 loops, best of 3: 0.787 usec per loop 

as can see map faster , more pythonic compared list comprehension. discussed in full length here

map may microscopically faster in cases (when you're not making lambda purpose, using same function in map , listcomp). list comprehensions may faster in other cases


another way using itertools.imap. fastest long lists

from itertools import imap totalcal = sum(imap(float,cals) 

and using timeit list 1000 entries.

$ python -m timeit "import random;cals = [str(random.randint(0,100)) r in range(1000)];sum(map(float,cals))" 1000 loops, best of 3: 1.38 msec per loop $ python -m timeit "import random;cals = [str(random.randint(0,100)) r in range(1000)];[float(i) in (cals)]" 1000 loops, best of 3: 1.39 msec per loop $ python -m timeit "from itertools import imap;import random;cals = [str(random.randint(0,100)) r in range(1000)];imap(float,cals)" 1000 loops, best of 3: 1.24 msec per loop 

as padraic mentions below, imap way best way go! fast1 , looks great! inclusion of library function has it's bearing on small lists , not on large lists. large lists, imap better suited.

1 list comprehension still slower map 1 micro second!!! thank god


Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -