以前面试的时候遇到过这个问题,今天闲着整理了以下,大概想到以下三种方法。
<span style="font-size:18px;">class delect_duplicate:
def method_set(self,mlist):
print("method_set is called")
print("before process mlist is", mlist)
l2 = set(mlist)
print("after processed by method_xunhuan, the mlist is",l2)
def method_xunhuan(self,mlist):
print("method_xunhuan is called")
print("before process mlist is", mlist)
if mlist:
mlist.sort()
last = mlist[-1]
for i in range(len(mlist) - 2, -1, -1):
if last == mlist[i]:
del mlist[i]
else:
last = mlist[i]
print("after processed by method_xunhuan, the mlist is",mlist)
def method3(self,mlist):
print("method3 is called")
print("before process mlist is", mlist)
temp = []
[temp.append(i) for i in mlist if not i in temp]
print("after processed by method3, the result is",temp)</span>
第一种方法直接用set方法,简单粗暴有效,但是因为太简单,往往不能满足面试官的,
第二种方法是对列表的元素排序后从后往前比较,去除相同元素,但是前两种方法都有一个缺点,就是处理后元素的位置改变了,
第三种方法是用两个列表进行处理,不改变元素的位置,测试代码如下:
<span style="font-size:18px;">if __name__ == '__main__':
A = [1, 5, 4, 8, 9, 2, 4, 5, 1]
B = [1, 5, 4, 8, 9, 2, 4, 5, 1]
C = [1, 5, 4, 8, 9, 2, 4, 5, 1]
s = delect_duplicate()
s.method_set(A)
s.method_xunhuan(B)
s.method3(C)</span>
运行结果如下:
<span style="font-size:18px;">method_set is called
before process mlist is [1, 5, 4, 8, 9, 2, 4, 5, 1]
after processed by method_xunhuan, the mlist is {1, 2, 4, 5, 8, 9}
method_xunhuan is called
before process mlist is [1, 5, 4, 8, 9, 2, 4, 5, 1]
after processed by method_xunhuan, the mlist is [1, 2, 4, 5, 8, 9]
method3 is called
before process mlist is [1, 5, 4, 8, 9, 2, 4, 5, 1]
after processed by method3, the result is [1, 5, 4, 8, 9, 2]</span>
完整代码:https://github.com/wlseu/delectdumplicate