csvファイルを読み込み、6,7月の売上を表示する事が課題です。
Errorは出ませんが、7月が0円でないのに(870円)、0円と出てしまいます。
試しに、6月の部分を消したところ、正常に作動しましたので関数を呼び出す部分周辺が怪しそうなのですが...。
ちなみに、csvファイルには各行にカンマ(,)区切りで 日付(yyyy-mm-dd hh:mm:ss)、 品目、 売り上げ金額 の順に入力されています。
ex)2014-07-14 13:36:59,オレンジジュース,110
また、プログラミング初心者なので、正誤問わず書き方に指摘や改善点等ございましたら、その点もご教授願います。
Python
1"""月ごとの売上金額の集計.""" 2import csv 3from datetime import datetime 4 5ENCODING = 'utf-8' 6KEYS_LIST = ['date', 'name', 'price'] 7 8 9def count(dict_list, month): 10 """ 指定した month の name, price をカウントしてcount_name, count_priceを返す 11 """ 12 count_name = {} 13 count_price = 0 14 for a_dict in dict_list: 15 date = datetime.strptime(a_dict['date'], '%Y-%m-%d %H:%M:%S') 16 if date.month == month: 17 name = a_dict['name'] 18 price = int(a_dict['price']) 19 count_price += price 20 print(count_price) 21 if name in count_name.keys(): 22 count_name[name] += 1 23 else: 24 count_name[name] = 1 25 return count_name, count_price 26 27 28def main(): 29 with open('input/report.csv', encoding=ENCODING) as file: 30 dict_list = csv.DictReader(file, fieldnames=KEYS_LIST) 31 count_name_6, count_price_6 = count(dict_list, 6) 32 print('6月: {}'.format(count_price_6)) 33 count_name_7, count_price_7 = count(dict_list, 7) 34 print('7月: {}'.format(count_price_7)) 35 36if __name__ == '__main__': 37 main() 38
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/02/20 04:32
2018/02/20 04:49
2018/02/20 04:53
2018/02/20 05:09
2018/02/20 05:11
2018/02/20 05:20