2017-06-07 75 views
-1

我目前正在從Web API中提取數據,我試圖根據以下條件過濾一些值:計算用戶在兩個給定日期之間出現的次數,但僅限於他/她已經購買的物品樹莓派,香蕉PI和覆盆子PI2,而不是項目樹莓PI3在Python中限制計數器集合

,我收到具有以下結構的JSON對象:

[{ 
user_id : 0001 
CreatedOn: "2017-02-16 15:54:48", 
item: "raspbery pi", 
VIP: "YES", 
Vendor_CODE: "XYZ12345", 
}, 
{ 
user_id : 0001 
CreatedOn: "2017-02-15 13:49:16", 
item: "raspbery pi2", 
VIP: "YES", 
Vendor_CODE: "XYZ67890", 
}, 
{ 
user_id : 0001 
CreatedOn: "2017-02-10 15:54:48", 
item: "raspbery pi", 
VIP: "YES", 
Vendor_CODE: "RST171820", 
}, 
{ 
user_id : 0001 
CreatedOn: "2017-01-01 21:51:13", 
item: "raspbery pi3", 
VIP: "YES", 
Vendor_CODE: "XOL002321", 
}, 
{ 
user_id : 0005 
CreatedOn: "2017-01-30 17:34:18", 
item: "raspbery pi", 
VIP: "YES", 
Vendor_CODE: "RST171820", 
}, 
{ 
user_id : 0005 
CreatedOn: "2017-05-30 09:04:08", 
item: "banana pi", 
VIP: "YES", 
Vendor_CODE: "ITI342027", 
}] 

目前,我有以下的代碼,計數用戶出現兩次日期的次數。

from django.shortcuts import render 
from django.http import JsonResponse 
from rest_framework.views import APIView 
from rest_framework.response import Response 
from collections import Counter 
from datetime import datetime, timedelta 
import json, urllib.request, dateutil.parser, urllib.parse, 

#Request a response to the Web API 
def get_data(request, *args, **kwargs): 
    # YYYY-MM-DD 
    start_date = datetime.now() - timedelta(days=7) 
    end_date = datetime.now() - timedelta(days=1) 

    with urllib.request.urlopen("http://10.61.202.98:8081/T/ansdb/api/rows/dev/ect",timeout=15) as url: 
    response_data = json.loads(url.read().decode()) 

    #count the number of times the user appears when he bought the 4 items in two given dates 
    count_user_01 = Counter([k['user_id'] for k in response_data if 
     start_date_week < dateutil.parser.parse(k.get('CreatedOn')) < end_date_week]) 

我的方法是添加一些額外的「條件」來算,除了項目樹莓PI3所有物品,像:

count_user_01 = Counter([k['user_id'] for k in response_data if 
    start_date_week < dateutil.parser.parse(k.get('CreatedOn')) < end_date_week] and k['item']!='raspberry pi3') 

但如果我這樣做,那麼我會遇到的錯誤布爾對象是不可迭代的,我想我收到此錯誤,因爲收集計數器不允許我這樣做。

我的問題是:

  1. 我怎樣才能實現這個額外的條件到列表中,所以我可以算,除了覆盆子PI3所有的項目,是由一個用戶買的?

  2. 目前,我正在計算爲特定用戶購買的物品,但是如何計算所有用戶購買的所有物品?

歡迎提出所有意見,解答和建議。

更新

問題1解決方案是修復在括號中的問題。

count_user_01 = Counter([k['user_id'] for k in response_data if 
start_date_week < dateutil.parser.parse(k.get('CreatedOn')) < end_date_week and k['item']!='raspberry pi3']) 
+0

檢查括號。 – user2357112

+0

you mean count_user_01 = Counter([k ['user_id'] for k in response_data if start_date_week

回答

0

我覺得你的括號有問題。試試這個:

count_user_01 = Counter([k['user_id'] for k in response_data if 
    start_date_week < dateutil.parser.parse(k.get('CreatedOn')) < end_date_week and k['item']!='raspberry pi3']) 
+0

這個解決方案幫助我解決了問題1,但是我怎樣才能讓這些代碼適用於問題2? –