[Python] 데이터 엮기 zip()

tacowasabii·2024년 6월 11일
0

Python

목록 보기
2/12
post-thumbnail

zip() 함수는 여러 개의 iterable 객체를 받아 각 객체의 원소를 튜플 형태로 묶어주는 함수다. 이 글에서는 zip() 함수의 기본 사용법과 다양한 활용 예제를 알아본다.


기본 사용법

zip() 함수는 여러 iterable 객체를 인자로 받아, 해당 객체들의 원소를 순서대로 묶은 튜플을 반환한다.

예제

fruits = ["apple", "banana", "cherry"]
colors = ["red", "yellow", "red"]
for pair in zip(fruits, colors):
    print(pair)
# 출력 결과:
# ('apple', 'red')
# ('banana', 'yellow')
# ('cherry', 'red')

위 예제는 fruits 리스트와 colors 리스트를 zip() 함수로 묶어, 각 튜플을 순서대로 출력한다.

병렬 처리

여러 iterable 객체를 동시에 순회하면서 처리할 때 유용하다.

예제

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
cities = ["New York", "Los Angeles", "Chicago"]
for name, age, city in zip(names, ages, cities):
    print(name, age, city)
# 출력 결과:
# Alice 25 New York
# Bob 30 Los Angeles
# Charlie 35 Chicago

위 예제는 세 개의 리스트를 동시에 순회하며 각 원소를 출력한다.

데이터 해체 (Unzip)

zip() 함수로 묶인 데이터를 다시 해체할 수 있다.

예제

numbers = (1, 2, 3)
letters = ("A", "B", "C")
pairs = list(zip(numbers, letters))
print(pairs)
# 출력 결과:
# [(1, 'A'), (2, 'B'), (3, 'C')]

numbers, letters = zip(*pairs)
print(numbers)
# 출력 결과:
# (1, 2, 3)
print(letters)
# 출력 결과:
# ('A', 'B', 'C')

zip(*pairs)pairs 리스트를 원래의 튜플 형태로 되돌린다.

사전 변환

두 개의 리스트나 튜플을 사전(dictionary)으로 쉽게 변환할 수 있다.

예제

keys = ["name", "age", "city"]
values = ["Alice", 25, "New York"]
dictionary = dict(zip(keys, values))
print(dictionary)
# 출력 결과:
# {'name': 'Alice', 'age': 25, 'city': 'New York'}

날짜 데이터 예제

fields = ["year", "month", "day"]
values = [2024, 6, 11]
date_dict = dict(zip(fields, values))
print(date_dict)
# 출력 결과:
# {'year': 2024, 'month': 6, 'day': 11}

주의 사항

zip() 함수로 넘기는 인자의 길이가 다를 때는 가장 짧은 인자를 기준으로 묶인다.

예제

animals = ["cat", "dog", "rabbit"]
sounds = ["meow"]
print(list(zip(animals, sounds)))
# 출력 결과:
# [('cat', 'meow')]

위 예제에서 sounds 리스트의 길이가 짧기 때문에, 가장 짧은 인자를 기준으로 결과가 반환된다.

profile
웹 프론트엔드 엔지니어

0개의 댓글

관련 채용 정보