如何从列表中删除所有重复项 [英] How to remove all duplicate items from a list

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

问题描述

我将如何使用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.

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

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