0

I am using the following query to obtain company from a database:

companies = Company.objects.order_by('submit_time').reverse()

The output I get:

2013-11-13 12:25:30+00:00 <--- delete

2013-11-13 12:25:30+00:00 <--- keep

2013-11-13 12:25:14+00:00 <--- keep

2013-11-13 12:25:13+00:00 <--- delete

2013-11-13 12:25:13+00:00 <--- keep

2013-11-13 05:11:55+00:00 <--- delete

2013-11-13 05:11:55+00:00 <--- keep

2013-11-13 05:11:29+00:00 <--- delete

2013-11-13 05:11:29+00:00 <--- keep

2013-11-13 05:11:28+00:00 <--- keep

The company submit time contains duplicates. I am using the code to find companies submitted at the same time:

seen = set()
result = []
for item in companies:
    if item not in seen:
        seen.add(item.submit_time)
        result.append(item.submit_time)

What would be a way to adjust the following code so I could find the duplicate company time submission and delete the company with the latest time and keep the company with the earlier time? Thanks!

4

1 回答 1

0

当重复是时间本身时,我不明白“删除最新时间的公司并保留更早的时间”这一点。即不早也不晚

你不能:

seen = set()
result = []
for item in companies:
    if item.submit_time not in seen:
        seen.add(item.submit_time)
        result.append(item.submit_time)
    else:
        item.delete()

更新:

seen = {}
result = []
for item in companies:
    if item.submit_time not in seen:
        seen[item.submit_time] = item
        result.append(item.submit_time)
    else:
        seen[item.submit_time].delete()
        seen[item.submit_time] = item
于 2013-11-13T13:22:39.117 回答