2017-10-12 59 views
-2

鉴于在酒店人的逗留天以下JSON对象每三个月:如何计算连续事件?

[{u'month': u'7', u'stay_days': {u'value': 1.0}}, 
{u'month': u'8', u'stay_days': {u'value': 1.0}}, 
{u'month': u'9', u'stay_days': {u'value': 1.0}}] 

我应该检查,如果人在最近3个月连续2个月参观了酒店,每月至少一次。

我被检查连续访问卡住了。

arr = '''[ { 
      "stay_days": { 
       "value": 1.0 
      }, 
      "month": "1" 
     }, 
     { 
      "stay_days": { 
       "value": 1.0 
      }, 
      "month": "2" 
     }, 
     { 
      "stay_days": { 
       "value": 1.0 
      }, 
      "month": "3" 
     }]''' 
json_object = json.loads(arr) 
dt = datetime.strptime(datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%f'), "%Y-%m-%dT%H:%M:%S.%f") 
month = dt.month 
months = [] 
for line in json_object: 
    months.append(line["key"]) 
months 

if (int(month) - int(max(months))) > 0 and (int(month) - int(max(months))) <= 3: 
    for line in json_object: 
     # ??? 

回答

0

而不是使用日期时间来得到当前的月份,你可以得到更容易的使用时间:

current_month = int(time.strftime('%m')) 

而不是仅仅把整个JSON对象到列表中,你可以过滤掉从任何数据比月3个月前,也过滤掉任何个多月,没有任何停留天:

months = [] 
for line in json_object: 
    if current_month - int(line['month']) < 3 and line['stay_days']['value'] > 0: 
     months.append(int(line['month'])) 

如果我们几个月排序(逆向排序用来将最近到顶部),并通过迭代如果有两个相邻的月份,那么该人在最后3个连续2个月访问了酒店。

months.sort(reverse=True) 
consecutive_months = False 
print(months) 
for i in range(len(months) - 1): 
    if months[i] - months[i+1] == 1: 
     consecutive_months = True 
     break 

if consecutive_months: 
    print('Visited hotel during 2 consecutive months out of the last 3')