Python 比较日期、价格、名称和类别,打印最赚钱的名称

Python 比较日期、价格、名称和类别,打印最赚钱的名称,python,file,Python,File,我正在制作一个程序,它可以打印文件中日期范围内的每个类别中最有利可图的元素 date_cat_profit_dict = {} with open("data.txt") as f: for line in f: date, category, name, profit = line.split("|") profit = int(profit) composite_key = "{0}|{1}".format(date, catego

我正在制作一个程序,它可以打印文件中日期范围内的每个类别中最有利可图的元素

date_cat_profit_dict = {}

with open("data.txt") as f:
    for line in f:
        date, category, name, profit = line.split("|")
        profit = int(profit)

        composite_key = "{0}|{1}".format(date, category)

        _, max_profit = (date_cat_profit_dict.setdefault(composite_key, ("", 0)))

        if max_profit < profit:
            date_cat_profit_dict[composite_key] = (name, profit)

for composite_key, (name, profit) in date_cat_profit_dict.items():
    print("{0} --> {1}".format(composite_key, name))
日期将始终在结束顺序上

问题:

我必须实现日期范围为o的用户条目。此程序将打印所有文件。另外,我有两个不同的名字为一个类别

此程序的示例。

我的预期结果:

当程序启动时,它要求我的开始日期和结束日期,在此之后,它将打印每个类别最有利可图的元素

输入:

开始日期:2016年1月7日

完:2016年1月8日

输出:

类别1:名称2

类别2:名称2


Category3:Name3

与其提供详细的代码,不如提供缺少的部分

日期时间比较工具

>>> import time
>>> date_1 = time.strptime('08/01/2016','%d/%m/%Y')
>>> print date_1
time.struct_time(tm_year=2016, tm_mon=1, tm_mday=8, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=8, tm_isdst=-1)
>>> date_2 = time.strptime('09/01/2016','%d/%m/%Y')
>>> print date_2
time.struct_time(tm_year=2016, tm_mon=1, tm_mday=9, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=9, tm_isdst=-1)
>>> 
>>> date_1 < date_2
True
备选案文2:

date_cat_profit_dict[(date_str, cat_str)] = dict()
date_cat_profit_dict[(date_str, cat_str)]['name'] = name
date_cat_profit_dict[(date_str, cat_str)]['profit'] = profit
date_cat_profit_dict[(date_str, cat_str)]['date'] = date_1 #date object

希望它能帮助你找到解决问题的正确方法。

我不知道你在这里做了什么。
>>> import time
>>> date_1 = time.strptime('08/01/2016','%d/%m/%Y')
>>> print date_1
time.struct_time(tm_year=2016, tm_mon=1, tm_mday=8, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=8, tm_isdst=-1)
>>> date_2 = time.strptime('09/01/2016','%d/%m/%Y')
>>> print date_2
time.struct_time(tm_year=2016, tm_mon=1, tm_mday=9, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=9, tm_isdst=-1)
>>> 
>>> date_1 < date_2
True
date_cat_profit_dict[date_str] = dict()
date_cat_profit_dict[date_str][cat_str] = dict()
date_cat_profit_dict[date_str][cat_str]['name'] = name
date_cat_profit_dict[date_str][cat_str]['profit'] = profit
date_cat_profit_dict[date_str][cat_str]['date'] = date_1 #date object
date_cat_profit_dict[(date_str, cat_str)] = dict()
date_cat_profit_dict[(date_str, cat_str)]['name'] = name
date_cat_profit_dict[(date_str, cat_str)]['profit'] = profit
date_cat_profit_dict[(date_str, cat_str)]['date'] = date_1 #date object