Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python에서 튜플 리스트를 두 번째 요소 기준으로 그룹화하는 방법

이 튜토리얼에서는 리스트에 담긴 튜플들을 두 번째 요소가 같은 것끼리 묶어 그룹화하는 프로그램을 작성해 보겠습니다. 먼저 예시를 통해 문제를 명확하게 이해해 봅시다.

입력 예시

[('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 'tutorialspoints'),
('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'other')]

출력 결과

{'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints')],
'other': [('Management', 'other'), ('Social', 'other'), ('Business', 'other')]}

즉, 리스트 안의 튜플들을 두 번째 요소(카테고리)별로 분류하여 하나의 딕셔너리로 만들어야 합니다. 문제 해결 과정을 단계별로 살펴보겠습니다.

  • 필요한 튜플들이 담긴 리스트를 초기화합니다.
  • 결과를 저장할 빈 딕셔너리를 생성합니다.
  • 튜플 리스트를 순회하며 다음을 확인합니다.
    • 튜플의 두 번째 요소가 이미 딕셔너리의 키로 존재하는지 검사합니다.
    • 존재한다면 현재 튜플을 해당 키의 리스트에 추가합니다.
    • 존재하지 않는다면 해당 키를 새로 만들고, 현재 튜플을 담은 리스트로 초기화합니다.
  • 순회가 끝나면 원하는 형태로 그룹화된 딕셔너리를 얻게 됩니다.

예제 코드 1: 일반 딕셔너리 사용

# 튜플이 담긴 리스트 초기화
tuples = [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 'tutorialspoints'),
('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'other')]

# 빈 딕셔너리 생성
result = {}

# 튜플 리스트 순회
for tup in tuples:
# 두 번째 요소가 딕셔너리에 있는지 확인
if tup[1] in result:
# 있다면 현재 튜플을 해당 리스트에 추가
result[tup[1]].append(tup)
else:
# 없다면 키를 새로 만들고 리스트로 초기화
result[tup[1]] = [tup]

# 결과 출력
print(result)

실행 결과

위 코드를 실행하면 다음과 같은 결과를 얻을 수 있습니다.

{'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints')],
'other': [('Management', 'other'), ('Social', 'other'), ('Business', 'other')]}

예제 코드 2: defaultdict 활용하기

위 프로그램에서는 매번 if 조건문으로 키의 존재 여부를 직접 확인해야 했습니다. collections 모듈의 defaultdict를 사용하면 이 조건문을 생략할 수 있습니다. defaultdict는 존재하지 않는 키에 접근할 때 자동으로 기본값(여기서는 빈 리스트)을 생성해 주기 때문입니다.

# collections 모듈에서 defaultdict 임포트
from collections import defaultdict

# 튜플이 담긴 리스트 초기화
tuples = [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 'tutorialspoints'),
('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'other')]

# 기본값이 리스트인 defaultdict 생성
result = defaultdict(list)

# 튜플 리스트 순회
for tup in tuples:
result[tup[1]].append(tup)

# 결과 출력
print(dict(result))

실행 결과

위 코드를 실행하면 첫 번째 예제와 동일한 결과를 얻을 수 있습니다.

{'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints')],
'other': [('Management', 'other'), ('Social', 'other'), ('Business', 'other')]}

마무리

지금까지 튜플 리스트를 두 번째 요소 기준으로 그룹화하는 두 가지 방법을 살펴보았습니다. 일반 딕셔너리와 조건문을 사용하는 방법과 defaultdict를 활용해 코드를 더 간결하게 만드는 방법이 있으며, 상황에 맞게 선택하여 사용하시면 됩니다. 튜토리얼에 대해 궁금한 점이 있다면 댓글로 남겨주세요.