![](/img/trans.png)
[英]How to remove first occurrence of a specific item from a list of items without using .pop() or .remove()
[英]Deleting specific items from list using pop
我有一個學校作業要從輸入列表中刪除特定元素。 具體細節如下:
您要做的是:
例如:如果輸入為[1、2、3、4、3、6、3、8],則輸出應為[1、2、3、4、3、6、8]
但是,您不能:
到目前為止,這是我得到的:
l=[]
mid=0
found=0
for m in range(0,10):
num=int(input("Enter the numbers for the list(10)"))
l.append(num)
nan=int(input("Enter the number which u want to remove"))
for i in range(0,10):
if l[i]==nan:
mid=i
for j in range(mid,10):
if l[j]==nan:
found=1
mid=j
for k in range(mid,9):
l[k]=l[k+1]
break
if nan not in l:
found==-1
if found==1:
l.pop()
print (l)
if found==-1:
print("Number doesnt exist in given list")
但是我不明白該程序是如何工作的。 應該刪除第二個出現的輸入元素,而不是最后一個。
例如,如果列表為:[1、2、3、2、5、6、7、2、9、10]結果不應該為:[1、2、3、5、6、7、2 ,9、10]? 如果沒有,為什么? 如果有人可以向我解釋,那將是很大的幫助!
l = [1, 2, 3, 4, 3, 6, 3, 8]
seen = set()
duplicates = []
remove_after_occurrence = 3
for number in l:
if number not in seen:
seen.add(number)
else:
if number not in duplicates:
duplicates.append(number)
counter = 0
for remove in duplicates:
for index, number in enumerate(l):
if remove == number:
counter += 1
if counter == remove_after_occurrence:
l.pop(index)
counter = 0
print(l)
print(seen)
print(duplicates)
此解決方案使用一組來指示重復值。 然后用pop刪除列表中的重復值。 它有點容易閱讀。
d = dict()
elements = [1, 2, 3, 4, 3, 6, 3, 8]
for i, element in enumerate(elements):
if elements.count( element ) > 1:
d[element] = i
for j in d.values():
elements.pop( j )
print elements
這將重復元素的索引存儲為最新的元素,然后一個一個地刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.