gpt4 book ai didi

python - 返回元组列表中的唯一记录以及具有最大日期时间的非唯一记录

转载 作者:太空宇宙 更新时间:2023-11-03 14:42:16 24 4
gpt4 key购买 nike

我有一个如下所示的元组列表:

temp = [
(1676L, 530L, 'please submit your lab', datetime.datetime(2017, 9, 29, 11, 10, 18), None),
(1677L, 527L, 'this is not the message youre looking for', datetime.datetime(2017, 9, 29, 11, 50, 27), None),
(1675L, 529L, 'hi. please come to my office at 5', datetime.datetime(2017, 9, 29, 11, 10, 8), None),
(1678L, 529L, 'hi. please come to my office at 6', datetime.datetime(2017, 9, 29, 11, 50, 56), None),
(1674L, 528L, 'hi, my name is John', datetime.datetime(2017, 9, 29, 11, 9, 40), None),
(543L, 527L, 'hi, this is message No 499', datetime.datetime(2017, 9, 26, 17, 53, 22), None)
(1630L, 527L, 'hi, I love you', datetime.datetime(2017, 9, 28, 17, 50, 00), None)
]

元组中的第二项是 ids (530,527 等),第四项是日期时间。列表中可能有多个记录具有相同的 id(即第二条、第六条和第七条记录的 id = 527)。

如何在 python 中编写返回唯一记录的代码(它们的 id 仅显示一次),如果它们不唯一(列表中有多个具有相同 id 的记录),则仅返回具有最大日期时间的记录?

最佳答案

您可以使用 dictionary 轻松完成此操作,以第二列作为键。使用日期时间列按升序对列表进行排序。由于键不能重复,因此您将获得最后一个值(如果键相同,则值更高)。要获取列表,只需访问 values

#sort by datetime [3] col
new_t = sorted(temp,key=lambda x: x[3])

#create dictionary with the [1] column as key
max_dict = { x[1]: x for x in new_t }

#get the required list
print([val for val in max_dict.values()])

#驱动程序值

IN : 
temp = [ (1676L, 530L, 'please submit your lab', datetime.datetime(2017, 9, 29, 11, 10, 18), None),
(1677L, 527L, 'this is not the message youre looking for', datetime.datetime(2017, 9, 29, 11, 50, 27), None),
(1675L, 529L, 'hi. please come to my office at 5', datetime.datetime(2017, 9, 29, 11, 10, 8), None),
(1678L, 529L, 'hi. please come to my office at 6', datetime.datetime(2017, 9, 29, 11, 50, 56), None),
(1674L, 528L, 'hi, my name is John', datetime.datetime(2017, 9, 29, 11, 9, 40), None),
(543L, 527L, 'hi, this is message No 499', datetime.datetime(2017, 9, 26, 17, 53, 22), None),
(1630L, 527L, 'hi, I love you', datetime.datetime(2017, 9, 28, 17, 50, 00), None) ]

OUT :
[(1674L, 528L, 'hi, my name is John', datetime.datetime(2017, 9, 29, 11, 9, 40), None),
(1678L, 529L, 'hi. please come to my office at 6', datetime.datetime(2017, 9, 29, 11, 50, 56), None),
(1676L, 530L, 'please submit your lab', datetime.datetime(2017, 9, 29, 11, 10, 18), None),
(1677L, 527L, 'this is not the message youre looking for', datetime.datetime(2017, 9, 29, 11, 50, 27), None)]

关于python - 返回元组列表中的唯一记录以及具有最大日期时间的非唯一记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46494906/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com