Python列表解析删除重复项 [英] Python list comprehension Remove duplicates

查看:264
本文介绍了Python列表解析删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要 hubcode_list 中的独特元素。我可以通过

I want unique elements in hubcode_list. I can do it by

hubcode_alarm_obj = HubAlarm.objects.all()
for obj in hubcode_alarm_obj:
    hubcode = obj.hubcode
    if hubcode not in hubcode_list:
        hubcode_list.append(hubcode)

我想使用列表解析。我正在尝试这个,但它说 hubcode_list 是未定义的,这是正确的错误。如何才能在 hubcode_list

I want to use list comprehension. I'm trying this but it says hubcode_list is undefined, which is the correct bug. How can I only add unique elements in hubcode_list

hubcode_alarm_obj = HubAlarm.objects.all()
hubcode_list = [obj.hubcode for obj in hubcode_alarm_obj if obj.hubcode not in hubcode_list]

我也可以这样做: -

I can also do it by:-

hubcode_list = list(set([obj.hubcode for obj in hubcode_alarm_obj]))

但设置再次是另一个操作。可以通过在list-comprehension中使用 if-statement 来实现吗?

But set is again another operation. Can I do it by using if-statement in list-comprehension?

推荐答案

p>由于您正在使用django,请让数据库为您进行过滤。这将是(到目前为止)最快的选项:

Since you are using django, let the database do the filtering for you. It will be (by far) the fastest option:

objects = HubAlarm.objects.exclude(hubcode__in=hubcode_list)

请参见文档了解更多。

这篇关于Python列表解析删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆