Python Function returns wrong value -


periodslist = []  su = '0:' su = [] sun = [] sun = '' 

i'm formating timetables converting

extendedperiods = ['0: 1200 - 1500',     '0: 1800 - 2330',     '2: 1200 - 1500',     '2: 1800 - 2330',     '3: 1200 - 1500',     '3: 1800 - 2330',     '4: 1200 - 1500',     '4: 1800 - 2330',     '5: 1200 - 1500',     '5: 1800 - 2330',     '6: 1200 - 1500',     '6: 1800 - 2330'] 

into '1200 - 1500/1800 - 2330'

  • su day identifier
  • su, sun store values
  • sun stores converted timetable

    for line in  extendedperiods:   if su in line:         su.append(line)    item in su:     sun.append(item.replace(su, '', 1).strip())    sun = '/'.join([str(x) x in sun]) 

then tried write function apply "converter" other days..

def formatperiods(id, store1, store2, periodsday):    line in extendedperiods:     if id in line:           store1.append(line)    item in store1:     store2.append(item.replace(id, '', 1).strip())    periodsday = '/'.join([str(x) x in store2])     return periodsday      

but function returns 12 misformatted strings...

'1200 - 1500', '1200 - 1500/1200 - 1500/1800 - 2330', 

you can use collections.ordereddict here, if order doesn't matter use collections.defaultdict

>>> collections import ordereddict >>> dic = ordereddict() item in extendedperiods:     k,v = item.split(': ')     dic.setdefault(k,[]).append(v) ...      >>> k,v in dic.iteritems(): ...     print "/".join(v) ...      1200 - 1500/1800 - 2330 1200 - 1500/1800 - 2330 1200 - 1500/1800 - 2330 1200 - 1500/1800 - 2330 1200 - 1500/1800 - 2330 1200 - 1500/1800 - 2330 

to access particular day can use:

>>> print "/".join(dic['0'])   #sunday 1200 - 1500/1800 - 2330 >>> print "/".join(dic['2'])   #tuesday 1200 - 1500/1800 - 2330 

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -