如何从列表中删除所有重复项

编程入门 行业动态 更新时间:2024-10-08 11:00:04
本文介绍了如何从列表中删除所有重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我将如何使用python检查列表并删除所有重复项?我不需要指定重复项是什么-我希望代码找出是否存在重复项,如果有则将其删除,每个重复项仅保留一个实例.如果列表中有多个重复项,它也必须工作.

How would I use python to check a list and delete all duplicates? I don't want to have to specify what the duplicate item is - I want the code to figure out if there are any and remove them if so, keeping only one instance of each. It also must work if there are multiple duplicates in a list.

例如,在下面的代码中,列表lseparatedOrbList有12个项目-一项重复六次,一项重复五次,并且只有一个实例.我希望它更改列表,因此只有三项-一项,并且顺序与之前相同.我试过了:

For example, in my code below, the list lseparatedOrbList has 12 items - one is repeated six times, one is repeated five times, and there is only one instance of one. I want it to change the list so there are only three items - one of each, and in the same order they appeared before. I tried this:

for i in lseparatedOrbList: for j in lseparatedOrblist: if lseparatedOrbList[i] == lseparatedOrbList[j]: lseparatedOrbList.remove(lseparatedOrbList[j])

但是我得到了错误:

Traceback (most recent call last): File "qchemOutputSearch.py", line 123, in <module> for j in lseparatedOrblist: NameError: name 'lseparatedOrblist' is not defined

我猜是因为这是因为我在遍历lseparatedOrbList时试图遍历它,但我想不出另一种方法.

I'm guessing because it's because I'm trying to loop through lseparatedOrbList while I loop through it, but I can't think of another way to do it.

推荐答案

只要创建一个新列表即可,如果您列表中的项目尚未在新列表中输入,否则只需继续执行下一个项目即可.您的原始列表.

Just make a new list to populate, if the item for your list is not yet in the new list input it, else just move on to the next item in your original list.

for i in mylist: if i not in newlist: newlist.append(i)

我认为这是正确的语法,但是我的python有点不稳定,我希望您至少能理解.

I think this is the correct syntax, but my python is a bit shaky, I hope you at least get the idea.

更多推荐

如何从列表中删除所有重复项

本文发布于:2023-11-30 12:37:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649987.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!