본문 바로가기

프로그래밍 언어/python

중복 제거

1. SET

- 중복을 허용하지 않으며, set 내부 값들은 순서가 존재하지 않음

- 리스트 자료형을 SET으로 타입 변경 후 다시 LIST로 감싸줌

- list(set(array))

- set 타입은 print시 중괄호 {}, 리스트는 print시 대괄호 []

 

2. for 반복문

array = [6,5,6,1,3,6,4,5,2]
result = []

for i in array:
	if value not in result:
    	result.append(value)

print(result)

 

3.dictionary(3.7 이상 가능 자료구조)

- 중복이 불가능한 자료구조

- key,value의 쌍으로 하나의 데이터를 이루는데, key값이 중복 불가함

-  dict.fromkeys( array ) : 인자로 들어온 array 데이터를 key값으로 해서 딕셔너리 자료형으로 만들어준다. 

- list( dict.fromkeys(array) )

 

 

*** 중복 제거하면서, 기존의 array 순서를 유지하고 싶을 때

1. dictionary 자료구조 이용

  - list ( dict.fromkeys(array) )

 

2. Set 자료구조를 sorted()함수로 정렬

 - sorted( set(array), key = lambda x : array.index(x)) 

 

3. Collection Pakage 의 OrderdDict 이용

from collections import OrderedDict

array = [1,3,5,4,4,5,7]

list ( collections.fromkeys(array) )

 

4.for문 

'프로그래밍 언어 > python' 카테고리의 다른 글

수학  (0) 2021.07.29
python 에러 모음  (0) 2021.07.28
python 기초 - 구현  (0) 2021.07.24
python 기초 - 배열1  (0) 2021.07.23
정렬  (0) 2021.07.21