我對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
...
什麼我們展示了文件內容和示例輸出的例子嗎? – Nf4r
嘗試使用[pprint](https://docs.python.org/3/library/pprint.html#pprint.pprint) – wwii
完成編輯... –