2017-03-27 15 views
0

我對Python很陌生,我需要製作代碼來計算每個數字出現在與特定鍵相關的列表中的次數。然後該程序應該在單獨的行上打印出這些計數。計算列表中的每個數字的外觀並將它們打印在不同的行上

我能夠打印出計數,但我無法在單獨的行上打印它們。這是我能到目前爲止做:

import json 

##### 

def read_json(filename): 
    dt = {} 

    fh = open(filename, "r") 
    dt = json.load(fh) 

    return dt 

##### 

def num_counter(dt): 

    numbers = dt["daily_stock_prices"] 


    counter = {} 

    for number in numbers: 
     counter[number] = 0 

    for number in numbers: 
     counter[number] += 1 

    print counter 

##### 

filename = raw_input('Please enter the file name: ') 

##### 

r = read_json(filename) 
num_counter(r) 

我試圖在打印上,如下圖所示單獨的行櫃檯工作,但我仍然不成功。有什麼建議?我也不確定將它包含在我的代碼中。

def print_per_line(number_counts): 

    for number in number_counts.key(): 

      count = word_counts[word]  

      print word,count 

這裏,如果需要的清單:

{ 
    "ticker": "MSFT", 
    "daily_stock_prices": [0,1,5,10,12,15,11,9,9,5,15,20] 
} 

最終的輸出應該是:

item: count 
item: count 
... 
+3

什麼我們展示了文件內容和示例輸出的例子嗎? – Nf4r

+0

嘗試使用[pprint](https://docs.python.org/3/library/pprint.html#pprint.pprint) – wwii

+0

完成編輯... –

回答

1

試試這個:

def num_counter(dt): 
    numbers = dt["daily_stock_prices"] 
    counter = {} 
    for number in numbers: 
     counter[number]= counter.get(number, 0) + 1 
    return counter 

def print_per_line(num_count): 
    for k,v in counter.iteritems(): 
     print str(k) + ": " + str(v) 

# You call them like this 
r = read_json(filename) 
num_count = num_counter(r) 
print_per_line(num_count) 
+0

是否可以繼續從我開始的代碼請 –

+0

@ J.Doe更新了答案,那是你在找什麼? – chinmay

+0

我不允許添加函數調用。對不起,忘了提及 –

0

這裏是如何做到這一點無論是否有collections模塊。

import collections 
import json 

# Here is the sample data 
data = """{ 
    "ticker": "MSFT", 
    "daily_stock_prices": [0,1,5,10,12,15,11,9,9,5,15,20] 
}""" 

# It's easiest to parses it with as JSON. 
d = json.loads(data) 

# You can use the collections module to count. 
counts = collections.Counter(d['daily_stock_prices']) 

# Or you can create a dictionary of the prices. 
pricedict = {} 
for price in d['daily_stock_prices']: 
    if pricedict.has_key(price): 
     pricedict[price] += 1 
    else: 
     pricedict[price] = 1 

# Print output - you could substitute counts for pricedict. 
for k,v in pricedict.iteritems(): 
    print("{} - {}".format(k, v)) 

輸出

0 - 1 
1 - 1 
5 - 2 
9 - 2 
10 - 1 
11 - 1 
12 - 1 
15 - 2 
20 - 1 
>>> 
+0

有沒有一種方法沒有使用集合。我還沒有得知這個命令 –

+0

@ J.Doe已經給出了沒有下面的答案 – chinmay

+0

是的 - 我會發布更新。集合模塊使得它更容易。剛纔看到chinmay展示瞭如何做到這一點。我會發布一些不同的東西,這樣你可以獲得Python的字典容器的句柄。 –

相關問題