简体   繁体   English

列出删除 Python 中的重复项

[英]List Remove Duplicates in Python

I'm having trouble getting my code to run.我无法让我的代码运行。 Any idea what is wrong with my code?知道我的代码有什么问题吗?

from random import randint
a=[]
b=[]
dup_list=[]
nodup_list=[]
for n in range (0,10):
    a.append(randint(0,20))
    b.append(randint(0,20))
print a, "\n"
print b, "\n"

for m in range(0, len(a)-1):
    if a[m] in b:
        dup_list.append(a[m])
    else:
        nodup_list.append(a[m])

for o in range(0,len(b)-1):
    if b[o] in a:
        b.remove(b[o])
nodup_list.append(b)

print dup_list, "\n"
print nodup_list,"\n"

I keep getting the error: [5, 17, 11, 18, 11, 20, 7, 16, 14, 14]我不断收到错误消息: [5, 17, 11, 18, 11, 20, 7, 16, 14, 14]

[Traceback (most recent call last): File "/Users/Apple/Desktop/Python/python projects/practice_python/exercise14.py", line 29, in 5, 3, 7, 8, 11, 18, 14, 9, 6, 18] [回溯(最近一次调用最后一次):文件“/Users/Apple/Desktop/Python/python projects/practice_python/exercise14.py”,第 29 行,在 5、3、7、8、11、18、14、9、 6、18]

if b[o] in a:

IndexError: list index out of range IndexError:列表索引超出范围

Any ideas why?任何想法为什么?

It's recommended in the python documentation to create a new list instead of iterating while removing. python 文档中建议创建一个新列表,而不是在删除时进行迭代。 The index is out of bounds because the list is shortened during iteration and so the index becomes greater than or equal to its size.索引超出范围,因为列表在迭代期间被缩短,因此索引变得大于或等于其大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM