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

Python의 List에서 중복 항목을 제거하는 방법을 배웁니다.

예제

목록에서 모든 중복 항목을 제거합니다:

mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)

예제 실행

예시 설명

먼저, 중복 항목이 포함된 List가 있습니다:

중복 항목이 포함된 목록

mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)

목록 항목을 키로 사용하여 딕셔너리를 생성합니다. 이렇게 하면 중복 항목이 자동으로 제거됩니다. 왜냐하면 사전은 중복 키를 가질 수 없기 때문입니다.

딕셔너리 생성

mylist = ["a", "b", "a", "c", "c"]
mylist = list( dict.fromkeys(mylist) )
print(mylist)

그런 다음, 딕셔너리를 다시 목록으로 변환합니다:

List로 변환합니다

mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist)) 
print(mylist)

지금 우리는 중복이 없는 List를 가지고 있습니다. 이 List는 원래 List와 같은 순서를 가집니다.

결과를 보여주기 위해 목록을 출력하십시오:

목록 출력

mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)

함수 생성

리스트를 전달하면 중복 없는 항목을 반환하는 함수를 만들고, 예제 코드를 삽입하려면 함수를 생성할 수 있습니다.

예제

def my_function(x):
  return list(dict.fromkeys(x))
mylist = my_function(["a", "b", "a", "c", "c"])
print(mylist)

예제 실행

예제 설명

리스트를 파라미터로 사용하는 함수를 생성하십시오.

함수 생성

def my_function(x): 
  return list(dict.fromkeys(x))
mylist = my_function(["a", "b", "a", "c", "c"])
print(mylist)

이 목록 항목을 키로 사용하여 딕셔너리를 생성하십시오.

딕셔너리 생성

def my_function(x):
  return list( dict.fromkeys(x) )
mylist = my_function(["a", "b", "a", "c", "c"])
print(mylist)

딕셔너리를 리스트로 변환:

리스트로 변환

def my_function(x):
  return list(dict.fromkeys(x)) 
mylist = my_function(["a", "b", "a", "c", "c"])
print(mylist)

리스트 반환:

리스트 반환

def my_function(x):
  return list(dict.fromkeys(x))
mylist = my_function(["a", "b", "a", "c", "c"])
print(mylist)

이 함수를 호출하기 위해 목록을 파라미터로 사용하십시오:

함수 호출

def my_function(x):
  return list(dict.fromkeys(x))
mylist = my_function(["a", "b", "a", "c", "c"])
print(mylist)

출력 결과:

출력 결과

def my_function(x):
  return list(dict.fromkeys(x))
mylist = my_function(["a", "b", "a", "c", "c"])
print(mylist)