對陣列 [3, 1, 2, 4, 2, 4, 5, 3, 7] 進行去重, 寫出至少兩種方法 (請寫出一段Python程式碼實現刪除一個list裡面的重複元素)
阿新 • • 發佈:2019-01-22
1. 對陣列 [3, 1, 2, 4, 2, 4, 5, 3, 7]
進行去重, 寫出至少兩種方法 (請寫出一段Python程式碼實現刪除一個list裡面的重複元素)
In [1]:def unique1(lst):
'''內建方法'''
return list(set(lst))
def unique2(lst):
'''思路簡單'''
l = []
for i in lst:
if i not in l:
l.append(i)
return l
def unique3(lst):
for i in lst.copy ():
if lst.count(i) > 1:
lst.remove(i)
return lst
def unique4(lst):
'''點陣圖去重, 僅限於正整數'''
bmp = 0
l = []
for i in lst:
n = (1 << i)
if bmp & n == 0:
bmp |= n
l.append(i)
return l
l = [3, 1, 2, 4, 2, 4, 2, 5, 3, 7]
print (unique1(l.copy()))
print(unique2(l.copy()))
print(unique3(l.copy()))
print(unique4(l.copy()))
[1, 2, 3, 4, 5, 7] [3, 1, 2, 4, 5, 7] [1, 4, 2, 5, 3, 7] [3, 1, 2, 4, 5, 7]