我是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
...
答案 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)
答案 1 :(得分: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
>>>