[python] zip() ํ•จ์ˆ˜

Minhee kangยท2021๋…„ 7์›” 23์ผ
0

Python

๋ชฉ๋ก ๋ณด๊ธฐ
14/25
# zip()ํ•จ์ˆ˜๋Š” ๋‹ค๋ฅธ ๊ทธ๋ฃน์˜ ๋ฐ์ดํ„ฐ๋ฅผ ์„œ๋กœ ์—ฎ์–ด์คŒ
# zip()ํ•จ์ˆ˜๋Š” ์—ฌ๋Ÿฌ๊ฐœ์˜ ์ˆœํšŒ๊ฐ€๋Šฅํ•œ(iterable) ๊ฐ์ฒด๋ฅผ input์œผ๋กœ ๋ฐ›์•„ 
# ์ˆœ์„œ๋Œ€๋กœ ์ง์„ ์ง€์–ด ํŠœํ”Œ์˜ ํ˜•ํƒœ๋กœ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐ˜๋ณต์ž(iterator)๋ฅผ return

nums = [1, 2, 3, 4]
letters = ['a', 'b', 'c']
for pair in zip(nums, letters):
    print(pair)
#(1, 'a')
#(2, 'b')
#(3, 'c')

nums = [1, 2, 3, 4]
letters_1 = ['A', 'B', 'C', 'D']
letters_2 = ['a', 'b', 'c', 'd']
for pair in zip(nums, letters_1, letters_2):
    print(pair)
#(1, 'A', 'a')
#(2, 'B', 'b')
#(3, 'C', 'c')
#(4, 'D', 'd')

# ๋ฌธ์ž์—ด์ด input์ผ ๊ฒฝ์šฐ
for pair in zip('1234', 'ABCD', 'abcd'):
    print(pair)
#('1', 'A', 'a')
#('2', 'B', 'b')
#('3', 'C', 'c')
#('4', 'D', 'd')

# ์—ฎ์–ด๋†“์€ ๋ฐ์ดํ„ฐ๋ฅผ ๋‹ค์‹œ ํ•ด์ œ(unzip)
# unpacking ์—ฐ์‚ฐ์ž *  ๋ถ™์—ฌ์„œ ๋‹ค์‹œ zip() ํ•จ์ˆ˜์— input
pairs = list(zip('1234', 'ABCD'))
print(pairs) #[('1', 'A'), ('2', 'B'), ('3', 'C'), ('4', 'D')]
nums, letters = zip(*pairs)
print(nums) #('1', '2', '3', '4')
print(letters) #('A', 'B', 'C', 'D')

#zip()ํ•œ ๊ฐ์ฒด๋ฅผ dictํ˜•ํƒœ๋กœ ๋ณ€ํ™˜
nums = [1, 2, 3]
letters = ['A', 'B', 'C']
print(dict(zip(nums, letters)))
#{1: 'A', 2: 'B', 3: 'C'}

#๊ธธ์ด๊ฐ€ ์•ˆ๋งž์„ ๊ฒฝ์šฐ => ์งง์€๊ฑธ ๊ธฐ์ค€์œผ๋กœ ์ƒ์„ฑํ•˜๊ณ  ๋‚˜๋จธ์ง€๋Š” ๋ฒ„๋ฆผ
numbers = ["1", "2", "3"]
letters = ['A']
print(list(zip(numbers, letters))) 
# ('1', 'A')]

๐Ÿ“’ zip() ํ™œ์šฉ - 2์ฐจ์› ๋ฐฐ์—ด ๋’ค์ง‘๊ธฐ

arr = ['1234', '1234', '1234', '1234']
print(list(zip(*arr)))  
#[('1', '1', '1', '1'), ('2', '2', '2', '2'), ('3', '3', '3', '3'), ('4', '4', '4', '4')]

arr2 = [[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]]
print(list(zip(*arr2)))
#[(1, 1, 1, 1), (2, 2, 2, 2), (3, 3, 3, 3), (4, 4, 4, 4)]

0๊ฐœ์˜ ๋Œ“๊ธ€