2016-02-10 37 views
0

我有這個json文件的問題:Zips.json! 。json文件(Python)的問題

我沒有找到一種方法來計算每個州的郵政編碼數量。我嘗試過很多辦法,如本:

file=open("C:\Users\Alex\Downloads/zips.json","r") 
lines=json.loads(file.readline()) 
number=0 
states=lines["state"] 
for line in file: 
    lines=json.loads(line) 
    if lines ["state"]==states: 
     number=number+1 
    else: 
     print u"states:",states, u"Number of codes: ",number 
     states=lines["state"] 
+0

感謝您的答覆,我加號= 0下我的人,但仍無法正常工作。 – Python241820

回答

2

要做到這一點,最簡單的方法是使用一個collections.Counter

import json 
from collections import Counter 
from operator import itemgetter 

counter = None 
state_getter = itemgetter('state') 

with open('zips.json') as fh: 
    zips_data = (json.loads(line) for line in fh) 
    states_names = map(itemgetter('state'), zips_data) 
    counter = Counter(states_names) 

print(counter) 
+0

非常感謝你,它完美的作品! @AndreyT – Python241820