2013-07-11 141 views
1
periodsList = [] 
su = '0:' 
Su = [] 
sun = [] 
SUN = '' 

我通過轉換Python函數返回錯誤值

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'] 

'1200 - 1500/1800 - 2330'

  • 蘇在格式化時間表是一天標識
  • 蘇,陽光店的一些值
  • SUN存儲轉換時間表

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

然後我試着寫爲也套用我的 「轉換器」 給其他日期的功能..

def formatPeriods(id, store1, store2, periodsDay): 
    for line in extendedPeriods: 
    if id in line:  
     store1.append(line) 

    for item in store1: 
    store2.append(item.replace(id, '', 1).strip()) 

    periodsDay = '/'.join([str(x) for x in store2]) 
    return periodsDay  

但該函數返回12個misformatted串...

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

你應該給你的變量不同的名字,你一定會混淆他們與這些名字。 – Dahaka

+0

您提供的輸入是爲了獲取這些格式錯誤的字符串而準確輸入的? – Th3Cuber

+0

formatPeriods(su,Su,sun,SUN) – user2560609

回答

2

您可以使用collections.OrderedDict這裏,如果訂單沒有按」牛逼事然後用collections.defaultdict

>>> from collections import OrderedDict 
>>> dic = OrderedDict() 
for item in extendedPeriods: 
    k,v = item.split(': ') 
    dic.setdefault(k,[]).append(v) 
...  
>>> for 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 

要訪問某一天,你可以使用:

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

這是您的一般邏輯:

from collections import defaultdict 

d = defaultdict(list) 

for i in extended_periods: 
    bits = i.split(':') 
    d[i[0].strip()].append(i[1].strip()) 

for i,v in d.iteritems(): 
    print i,'/'.join(v) 

輸出是:

0 1200 - 1500/1800 - 2330 
3 1200 - 1500/1800 - 2330 
2 1200 - 1500/1800 - 2330 
5 1200 - 1500/1800 - 2330 
4 1200 - 1500/1800 - 2330 
6 1200 - 1500/1800 - 2330 

爲了使功能一天,只需選擇d[0](星期日爲例):

def schedule_per_day(day): 

    d = defaultdict(list) 

    for i in extended_periods: 
     bits = i.split(':') 
     d[i[0].strip()].append(i[1].strip()) 

    return '/'.join(d[day]) if d.get(day) else None