Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python - 목록에서 중복을 제거하는 방법

<시간/>

목록은 중요한 컨테이너이며 웹 개발뿐만 아니라 일상적인 프로그래밍의 거의 모든 코드에서 사용됩니다. 사용할수록 목록을 마스터해야 하는 요구 사항도 많아지므로 작업에 대한 지식이 필요합니다. 목록에서 중복 제거 작업에는 많은 응용 프로그램이 있으므로 지식이 있으면 좋습니다.

# using naive methods
# initializing list
test_list = [1, 3, 5, 6, 3, 5, 6, 1]
print ("The original list is : " +  str(test_list))
# using naive method to remove duplicated from list
res = []
for i in test_list:
   if i not in res:
      res.append(i)
# printing list after removal
print ("The list after removing duplicates : " + str(res))
# using list comprehension
# initializing list
test_list = [1, 3, 5, 6, 3, 5, 6, 1]
print ("The original list is : " +  str(test_list))
# using list comprehension to remove duplicated from list
res = []
[res.append(x) for x in test_list if x not in res]
# printing list after removal
print ("The list after removing duplicates : " + str(res))
# using set()
# initializing list
test_list = [1, 5, 3, 6, 3, 5, 6, 1]
print ("The original list is : " +  str(test_list))
# using set() to remove duplicated from list
test_list = list(set(test_list))  
# printing list after removal
print ("The list after removing duplicates : " + str(test_list))
# using list comprehension + enumerate()
# initializing list
test_list = [1, 5, 3, 6, 3, 5, 6, 1]
print ("The original list is : " +  str(test_list))
# using list comprehension + enumerate() to remove duplicated from list
res = [i for n, i in enumerate(test_list) if i not in test_list[:n]]  
# printing list after removal
print ("The list after removing duplicates : " + str(res))
# using collections.OrderedDict.fromkeys()
from collections import OrderedDict
# initializing list
test_list = [1, 5, 3, 6, 3, 5, 6, 1]
print ("The original list is : " +  str(test_list))  
# using collections.OrderedDict.fromkeys() to remove duplicated from list
res = list(OrderedDict.fromkeys(test_list))  
# printing list after removal
print ("The list after removing duplicates : " + str(res))

출력

The original list is : [1, 3, 5, 6, 3, 5, 6, 1]
The list after removing duplicates : [1, 3, 5, 6]
The original list is : [1, 3, 5, 6, 3, 5, 6, 1]
The list after removing duplicates : [1, 3, 5, 6]
The original list is : [1, 5, 3, 6, 3, 5, 6, 1]
The list after removing duplicates : [1, 3, 5, 6]
The original list is : [1, 5, 3, 6, 3, 5, 6, 1]
The list after removing duplicates : [1, 5, 3, 6]
The original list is : [1, 5, 3, 6, 3, 5, 6, 1]
The list after removing duplicates : [1, 5, 3, 6]