2016-08-08 10 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"] 

は、これは私がリストを比較しています方法です:比較は唯一のCustomerNameに起こるが、unauthorizedCustomersリストはCustomerXの完全なデータを持つように

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

どのように上記のステートメントを修正しますか?

[{"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] 
関連する問題