Python/05 파이썬 심화
zip()
멍멍코
2023. 9. 7. 01:13
'zip()' 함수는 파이썬의 내장 함수로, 여러 개의 iterable 객체들의 원소를 짝지어 튜플로 묶어주는 역할을 합니다. 이 함수는 주로 여러 리스트나 튜플, 문자열등의 원소들을 동시에 순회하고 싶을 때 사용됩니다.
기본 사용법
for a, b in zip(list1, list2):
print(a, b)
설명
• 'zip()'은 여러 iterable 객체를 인자로 받아서 각 iterable의 같은 위치에 있는 원소들을 묶어서 튜플로 만들어 줍니다.
• 결과는 제일 짧은 iterable의 길이에 맞춰집니다. 즉, 입력되는 iterable 중 길이가 가장 짧은 것에 맞춰 결과가 생성됩니다.
사용 예제
fruits = ["apple", "banana", "cherry"]
colors = ["red", "yellow", "dark red"]
for fruit, color in zip(fruits, colors):
print(f"The color of {fruit} is {color}")
# 출력:
# The color of apple is red
# The color of banana is yellow
# The color of cherry is dark red
추가 정보
• 여러 개의 iterable을 동시에 'zip()'에 넣을 수도 있습니다. 예를 들어, 세 개의 리스트를 zip 함수에 넣으면 각 리스트의 원소들이 튜플로 묶여서 반환됩니다.
• 'zip()' 함수와 '*' 연산자를 함께 사용하면 원래의 iterable로 "unzip"할 수 있습니다.
zipped = zip(fruits, colors)
unzip_fruits, unzip_colors = zip(*zipped)
'zip()' 함수는 두 개 이상의 리스트나 iterable을 동시에 순회하거나, 여러 리스트의 원소들을 동시에 처리하고 싶을 때 아주 유용하게 사용될 수 있습니다.