python从列表中删除重复元素

潘胡里

在 python 中,我得到一个变量列表,如:

[ {'store_id': '321', 'first_name': 'A', 'name': 'A'}, 
{'second_id': '322', 'first_name': 'B', 'name': 'B', },
{'second_id': '323', 'second_name': 'c', 'name': 'c', },
{'second_id': '324', 'second_name': 'A', 'name': 'A', },
]

我真正想要的是我想要一个不重复名称的列表。如果它发生一次,那么我想删除 t 并创建一个具有不同数据的新列表。我被困在这里我想要新列表中的所有数据。如何从列表中删除重复数据。

就我而言,我想要一个 ne 列表,例如:

要么

{'second_id': '322', 'first_name': 'B', 'name': 'B', },
{'second_id': '323', 'second_name': 'c', 'name': 'c', },
{'second_id': '324', 'second_name': 'A', 'name': 'A', },
]

或者

[ {'store_id': '321', 'first_name': 'A', 'name': 'A'}, 
{'second_id': '322', 'first_name': 'B', 'name': 'B', },
{'second_id': '323', 'second_name': 'c', 'name': 'c', },

]

之后我得到的代码如下:

result = {}
    data = request.POST
    teamName = []

    First = Test.objects.filter(d=data.get('id')).values(
        'first_id','first_name').annotate(id=F('first_id'),name=F('first_name')).distinct()
    Second = Test.objects.filter(id=data.get('id')).values(
        'second_id','second_name').annotate(id=F('second_id'),name=F('second_name')).distinct()
    combined_results = list(chain(First, Second))


    for team in combined_results:
        team['text'] = team['name']
        team['id'] = team['id']
        teamName.append(team)

    if not combined_results:
        result['status'] = False
        result['data'] = ['Data not found']
    else:
        result['status'] = True
        result['data'] = teamName

    return JsonResponse(result)
湿婆

这应该给你第二种形式

names = set()
newList = []
for d in mylist:
    if d['name'] in names:
        continue
    else:
        newList.append(d)
        names.add(d['name'])

print(newList)

输出:

[{'store_id': '321', 'first_name': 'A', 'name': 'A'},
 {'second_id': '322', 'first_name': 'B', 'name': 'B'},
 {'second_id': '323', 'second_name': 'c', 'name': 'c'}]

编辑:
如果您想要第一种形式,则必须按store_id/ 的降序对原始列表进行排序second_id

mylist = sorted(mylist, key=lambda x: x.get('store_id') or x.get('second_id'), reverse=True)

然后像之前一样过滤列表。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章