Python,从元组列表中删除重复项

标签 python list items

我有以下列表:

[('mail', 167, datetime.datetime(2010, 9, 29)) , 
 ('name', 1317, datetime.datetime(2011, 12, 12)), 
 ('mail', 1045, datetime.datetime(2010, 8, 13)), 
 ('name', 3, datetime.datetime(2011, 11, 3))]

我想从列表中删除与日期不是最新的元组中的第一项重合的项目。换句话说,我需要得到这个:

[('mail', 167, datetime.datetime(2010, 9, 29)) , 
 ('name', 1317, datetime.datetime(2011, 12, 12))]

最佳答案

您可以使用字典来存储到目前为止为给定键找到的最高值:

temp = {}
for key, number, date in input_list:
    if key not in temp: # we see this key for the first time
        temp[key] = (key, number, date)
    else:
        if temp[key][2] < date: # the new date is larger than the old one
            temp[key] = (key, number, date)
result = temp.values()

关于Python,从元组列表中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6518071/

相关文章:

python - 上传内容为空的文件

python - 我们如何使用 python 从 ssh 代理运行 tmux

java - 保存到 LinkedHashSet <String> - 初学者

c# - 组合框自定义项和数据绑定(bind)项

python - 在 Python 字典中按两个值排列项目

python - Amazon Polly ProfileNotFound : The config profile (adminuser) could not be found

python - 如何根据第一个元素从嵌套列表中删除重复项,同时优先考虑列表的长度?

c - 多个链表

Android:在gridview中用线连接项目

python - 如何将元组从 Python 传递给 Matlab 函数