簡體   English   中英

列出刪除 Python 中的重復項

[英]List Remove Duplicates in Python

我無法讓我的代碼運行。 知道我的代碼有什么問題嗎?

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"

我不斷收到錯誤消息: [5, 17, 11, 18, 11, 20, 7, 16, 14, 14]

[回溯(最近一次調用最后一次):文件“/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:列表索引超出范圍

任何想法為什么?

python 文檔中建議創建一個新列表,而不是在刪除時進行迭代。 索引超出范圍,因為列表在迭代期間被縮短,因此索引變得大於或等於其大小。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM