1
periodsList = [] 
su = '0:'
Su = []
sun = []
SUN = ''

我正在通过转换来制定时间表

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'

  • su 是日期标识符
  • su、sun 存储一些值
  • 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 个格式错误的字符串...

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

2 回答 2

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
于 2013-07-11T10:31:05.623 回答
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
于 2013-07-11T10:30:54.370 回答