Skip to main content
 首页 » 编程设计

python之按日期对元组列表进行排序

2025年05月04日13zhujiabin

我想排序并返回按日期排序的元组的一部分。

我只想对第一个到第四个记录(元组[:3])进行排序并打印它。

tuple = [('Dec 1, 2010', '7.41', '7.60', '7.37'),  
         ('Dec 4, 2010', '7.41', '7.60', '7.37'),  
         ('Dec 2, 2010', '7.41', '7.60', '7.37'),  
         ('Dec 20, 2010', '7.41', '7.60', '7.37'),  
         ('Dec 16, 2010', '7.41', '7.60', '7.37'),  
         ('Jan 2, 2011', '7.41', '7.60', '7.37')] 

我试过:

import operator 
sorted(tuple[:3], key=operator.itemgetter('date'), reverse=True) 

但是,它返回错误“TypeError:元组索引必须是整数,而不是 str。

请您参考如下方法:

为什么要在 date 之前到达?元组的第一个元素不是您要找的吗?

sorted(records[:3], key=operator.itemgetter(0), reverse=True) 

顺便说一句,在比较它们之前,您应该将字符串转换为实际日期。也许:

from datetime import datetime 
def get_date(record): 
     return datetime.strptime(record[0], "%b %d, %Y") 
sorted(records[:3], key=get_date, reverse=True) 

我已将 tuple 重命名为 records。正如其他人指出的那样,通过使用 tuple 您正在隐藏类型构造函数;同样重要的是:它是一个列表而不是元组,变量应该是复数(因为它存储一个集合),并且它应该有一个有意义的名称。