# zip

https://www.daleseo.com/python-zip/

zip() 함수

여러 iterable(List, Tuple…) 객체를 인자로 받고,
인자로 받은 iterable을 병렬로 묶어서
각 객체가 담고 있는 원소를 Tuple형태로, 차례로 접근할 수 있는 iterator(반복자)를 반환

>> list(zip(['a','b','c','d','e'], [1,2,3]))

# [('a', 1), ('b', 2), ('c', 3)]

>> list(zip(['a','b','c']))

# [('a',), ('b',), ('c',)]
numbers = [1, 2, 3]
letters = ["A", "B", "C"]
zip(numbers, letters)  # iterator

for pair in zip(numbers, letters):
print(pair)
# (1, 'A')
# (2, 'B')
# (3, 'C')

for n, l in zip(numbers, letters):
print(n, l)
# 1 A
# 2 B
# 3 C

pairs = [(numbers[i], letters[i]) for i in range(3)]
# [(1, 'A'), (2, 'B'), (3, 'C')]

## list unpacking

a, b = zip(*pairs)        #unpacking *
print(a)
# (1, 2, 3)

print(b)
# ('A', 'B', 'C')

pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
numbers, letters = zip(*pairs)

print(numbers)  # (1, 2, 3)
print(letters)  # ('a', 'b', 'c')

## 여러 리스트를 동시에 순회하며 새로운 리스트 생성

for number, upper, lower in zip("12345", "ABCDE", "abcde"):
print(number, upper, lower)

# 1 A a
# 2 B b
# 3 C c
# 4 D d
# 5 E e

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]

summed_list = [x + y + z for x, y, z in zip(list1, list2, list3)]
print(summed_list)  # [12, 15, 18]

## dict 만들기

keys = [1, 2, 3]
values = ["A", "B", "C"]
dict(zip(keys, values))
# {1: 'A', 2: 'B', 3: 'C'}
Categories: Python Basic

Blog Owner

Subscribe
Notify of