我剛剛寫了一堆簡單的代碼,它必須洗掉串列中的重復項,但是有一個問題。有人可以解釋一下為什么它跳過了數字 3 嗎?
lis = [1, 1, 3, 4, 5, 5, 5, 6, 1, 1, 3, 6, 6, 6, 1, 4, 7, 6, 5]
for i in lis:
while lis.count(i) > 1:
print(f'removing {i} ... ')
lis.remove(i)
print(lis.count(i))
print(lis)
uj5u.com熱心網友回復:
只需獲取您的串列,將其轉換為集合,然后回傳串列:
listofthings = [1, 1, 3, 4, 5, 5, 5, 6, 1, 1, 3, 6, 6, 6, 1, 4, 7, 6, 5]
newlist=list(set(listofthings))
print(newlist)
uj5u.com熱心網友回復:
如果您不想洗掉所有 3 或所有 1,請不要使用 list.remove()
listofthings = [1, 1, 3, 4, 5, 5, 5, 6, 1, 1, 3, 6, 6, 6, 1, 4, 7, 6, 5]
for things in listofthings:
exists = 1
obj = things
cnt = 0
for things in listofthings:
cnt = cnt 1
dup = things
if dup == obj:
exists = exists 1
if exists == 2:
del listofthings[cnt]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/448619.html
