2016-08-08 49 views
1

這是我輸入的樣子的一部分:比較列表或設置JSON對象

inputData=[] 
inputData.append({"CustomerName": "CustomerA","State": "StateA","ItemNumber": "Item1"}) 
inputData.append({"CustomerName": "CustomerA","State": "StateA","ItemNumber": "Item2"}) 
inputData.append({"CustomerName": "CustomerB","State": "StateB","ItemNumber": "Item1"}) 
inputData.append({"CustomerName": "CustomerB","State": "StateB","ItemNumber": "Item2"}) 
inputData.append({"CustomerName": "CustomerX","State": "StateX","ItemNumber": "Item1"}) 
inputData.append({"CustomerName": "CustomerX","State": "StateX","ItemNumber": "Item2"}) 

這是我比較反對,以找出是否允許客戶購買的物品或不在名單。

allowedCustomers = ["CustomberA","CustomberB"] 

我這是怎麼比較列表:

unauthorizedCustomers = list(set(inputData)-set(allowedCustomers)) 

使得比較只發生客戶名稱,但unauthorizedCustomers列表中有CustomerX的完整的數據如何修改上面的語句?

[{"CustomerName": "CustomerX","State": "StateX","ItemNumber": "Item1"}, 
{"CustomerName": "CustomerX","State": "StateX","ItemNumber": "Item2"})] 

回答

1
>>> inputCustomerNames = [ item['CustomerName'] for item in inputData ] # get a list of input customer names only 
>>> unauthorizedCustomers = list(set(inputCustomerNames) - set(allowedCustomers)) # find unauthorized customers 
>>> unauthorizedCustomersDetails = [ item for item in inputData if item['CustomerName'] in unauthorizedCustomers ] # get all data of unauthorized customers 

你應該閱讀有關列表內涵理解這裏發生了什麼。 List Comprehensions

1

這裏是你可以使用JSON和名單做什麼:

import json 
inputData=[] 
inputData.append({"CustomerName": "CustomerA","State": "StateA","ItemNumber": "Item1"}) 
inputData.append({"CustomerName": "CustomerA","State": "StateA","ItemNumber": "Item2"}) 
inputData.append({"CustomerName": "CustomerB","State": "StateB","ItemNumber": "Item1"}) 
inputData.append({"CustomerName": "CustomerB","State": "StateB","ItemNumber": "Item2"}) 
inputData.append({"CustomerName": "CustomerX","State": "StateX","ItemNumber": "Item1"}) 
inputData.append({"CustomerName": "CustomerX","State": "StateX","ItemNumber": "Item2"}) 

allowedCustomers = ["CustomerA","CustomerB"] 
json_array = json.loads(json.dumps(inputData)) 
# Now filter required customer based on specific property. 
allowed_customers = [customer for customer in json_array if customer['CustomerName'] in allowedCustomers]