프로그래밍/Python

[python] zip() 내장함수 활용예제

히또아빠 2023. 10. 30. 16:14

zip은 파이썬의 내장 함수 중 하나로, 여러 개의 iterable(반복 가능한 객체)을 받아서 해당 iterable들에서 동일한 위치에 있는 요소들을 묶어 새로운 iterable을 생성합니다. 각 입력 iterable의 길이가 다를 경우, zip은 가장 짧은 iterable의 길이에 맞춰 짝을 지어줍니다.

zip(iterable1, iterable2, ...)

 

여기서 iterable1, iterable2, ...은 두 개 이상의 iterable 객체를 나타내며, zip 함수는 이러한 iterable들을 조합하여 새로운 iterable을 생성합니다.

예제 1: 두 리스트 묶기

names = ['Alice', 'Bob', 'Charlie']
scores = [90, 85, 88]

zipped = zip(names, scores)

for name, score in zipped:
    print(f'{name}: {score}')

이 코드는 namesscores 리스트를 묶어서 두 리스트에서 동일한 위치에 있는 요소들을 짝지어 출력합니다.

 

예제 2: zip과 *를 사용하여 리스트 언패킹

zip*를 함께 사용하여 iterable의 리스트를 다시 분리할 수도 있습니다.

Copy code
zipped = [('Alice', 90), ('Bob', 85), ('Charlie', 88)]
names, scores = zip(*zipped)

print(names)  # ('Alice', 'Bob', 'Charlie')
print(scores)  # (90, 85, 88)

예제 3: 길이가 다른 iterable 사용

zip은 iterable의 길이가 서로 다를 경우, 가장 짧은 iterable의 길이에 맞춰서 묶습니다.

list1 = [1, 2, 3]
list2 = ['a', 'b']

zipped = zip(list1, list2)

for item in zipped:
    print(item)
    
#(1, 'a')
#(2, 'b')

여기서는 list2의 길이가 짧기때문에 결과는 위와 같습니다.

300x250
반응형