我有一本这样的日期字典(这里的键与其他工作相关,需要考虑):
{2: ['8-12-2012', '9-12-2012', '7-12-2012],
5: ['10-12-2012', '11-12-2012'],
7: ['13-12-2012']}
现在,我想在每个列表中找出最早的日期。最后,我需要找出最早的日期,返回那个日期和钥匙。你知道吗
如果我手动执行此处尝试执行的操作:
**key 2**, `7-12-2012` is the earliest.
**key 5**, `10-12-2012` is the earliest.
**key 7**, `13-12-2012` is the earliest.
2012年7月12日是最早的日期,所以我应该返回2
。你知道吗
注意事项:
这是我尝试过的,但只比较了两个日期:
...
...
# this value would be dynamically set during runtime
expiryDates[item] = {2: ['8-12-2012', '9-12-2012', '7-12-2012], 5: ['10-12-2012', '11-12-2012'], 7: ['13-12-2012']}
datesInBox = []
dict_earliest_expiration = defaultdict(list)
for n in expiryDates:
datesInBox = expiryDates[n] # when n = 2; datesInBox = ['8-12-2012', '9-12-2012']
d1 = time.strptime(datesInBox[0], "%d-%m-%Y")
d2 = time.strptime(datesInBox[1], "%d-%m-%Y")
if d1 < d2:
dict_earliest_expiration[n] = d1
else:
dict_earliest_expiration[n] = d2
任何帮助都将不胜感激。你知道吗
我会慢慢来,让你看看这个过程。首先,反转指令:以时间为键,前一个键为值:
清理表示,
rev
现在现在只需最早打印钥匙:
如果你愿意,你可以把它折叠成一个听写理解和一个琐碎的调用。你知道吗
您可以将所有字符串转换为日期,然后使用min函数:
输出
或者,您可以预先计算字典中每个键的最小值:
输出
最后,您可以迭代键、值对,而不是迭代键:
输出
反复使用dict或直接传递密钥。将列表转换为熊猫系列并排序
输出
如果你只关心日期
输出:
根据给出的示例表示日期
输出:
相关问题 更多 >
编程相关推荐