从列表python中删除重复项 [英] Remove duplicates from list python

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

问题描述

我正在尝试编写一个从列表中删除重复项的程序,但是我的程序一直在第5行if n/(sequence[k]) == 1:上抛出错误列表索引超出范围".我不知道这一点.我认为"k"的可能值为0、1和2是正确的吗?那些索引中的任何一个的序列"如何超出可能的索引范围?

I'm trying to write a program that removes duplicates from a list, but my program keeps throwing the error "list index out of range" on line 5, if n/(sequence[k]) == 1:. I can't figure this out. Am I right in thinking that the possible values of "k" are 0, 1, and 2? How is "sequence" with any of those as the index outside of the possible index range?

def remove_duplicates(sequence):
    new_list = sequence
    for n in sequence:
        for k in range(len(sequence)):
            if n/(sequence[k]) == 1:
                new_list.remove(sequence[k])
    print new_list

remove_duplicates([1,2,3])

推荐答案

我强烈建议Akavall回答:

I strongly suggest Akavall's answer:

list(set(your_list))

关于为何超出范围错误的原因:Python通过引用传递,即sequence和new_list仍指向相同的内存位置.更改new_list也会更改顺序.

As to why you get out of range errors: Python passes by reference, that is sequence and new_list still point at the same memory location. Changing new_list also changes sequence.

最后,您正在将项目与其自身进行比较,然后将其删除.因此,基本上,即使您使用了序列的副本,例如:

And finally, you are comparing items with themselves, and then remove them. So basically even if you used a copy of sequence, like:

new_list = list(sequence)

new_list = sequence[:]

它将返回一个空列表.

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

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