[英]changing the original list inside function
需要創建一個函數,該函數一次刪除重復項,而不更改原始列表。 在第二個中,它需要更改原始列表並且不返回任何內容。 這里的問題是第二個函數只對一個重復起作用,而對兩個不同的數字不起作用(它只刪除一個數字(它對[2,3,4,5,3,4]不起作用,但是對[1,2, 3,3]
def drop_duplicates(lst):
s = []
# Write the rest of the code for question 3a below here.
for i in lst:
if i not in s:
s.append(i)
return s
lst = [1, 2, 3, 2, 4, 2]
print drop_duplicates(lst)
print lst
def drop_duplicates_in_place(lst):
# Write the rest of the code for question 3b below here.
for i in range(len(lst) - 1):
for j in range ( i+1, len(lst) - 1):
if lst[i] == lst[j]:
lst.pop(j)
else:
continue
lst = [1, 2, 3, 2, 4, 2]
print lst
內部循環范圍太短:
for i in range(len(lst) - 1):
for j in range(i+1, len(lst)): # no -1 here
此外,您實際上不需要在循環主體中使用else
部分。 通常,嵌套循環和從列表的(中間)重復刪除都不是理想的性能。 建議的方法也可以通過使用collections.OrderedDict
來刪除重復項,同時保持線性發生的順序。 要使其就位,可以使用切片分配:
from collections import OrderedDict
def drop_duplicates_in_place(lst):
lst[:] = OrderedDict.fromkeys(lst)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.