๐Ÿ“–zip(*iterables)

iterable ์ž๋ฃŒํ˜• ๊ฐ์ฒด๋ฅผ ์ธ์ž๋กœ ๋ฐ›์•„, ๋™์ผํ•œ ์ธ๋ฑ์Šค ์œ„์น˜์— ์žˆ๋Š” ๊ฐ๊ฐ์˜ element๋ฅผ ํŠœํ”Œ๋กœ ๋ฌถ์–ด ์ƒˆ๋กœ์šด iterable ์ž๋ฃŒํ˜•์„ ์ƒ์„ฑํ•˜๋Š” ํ•จ์ˆ˜

fruit = ["apple", "orange", "banana"]
color = ["red", "orange", "yellow"]
sweety = [30, 10, 1]
 
zipper = zip(fruit, color, sweety)
# [('apple', 'red', 30), ('orange', 'orange', 10), ('banana', 'yellow', 1)]
  • return zip ๊ฐ์ฒด

iterable ์ž๋ฃŒํ˜•์˜ ๊ฐœ์ˆ˜๊ฐ€ ๋™์ผํ•˜์ง€ ์•Š๋‹ค๋ฉด?

๊ฐ€์žฅ ์งง์€ iterable ๊ฐ์ฒด๊ฐ€ ์™„๋ฃŒ๋  ๋•Œ๊นŒ์ง€๋งŒ ์‹คํ–‰ ๊ธด ์ž๋ฃŒํ˜•๋“ค์˜ ๋‚˜๋จธ์ง€ element๋“ค์€ ์‚ฌ์šฉ๋˜์ง€ ์•Š์Œ

๐Ÿ“–์‚ฌ์šฉ ์˜ˆ์‹œ

๐Ÿ“ŽDictionary ๋งŒ๋“ค๊ธฐ

fruit = ["apple", "orange", "banana"]
color = ["red", "orange", "yellow"]
 
dict_zip = {f: c for f, c in zip(fruit, color)}
# {'apple': 'red', 'orange': 'orange', 'banana': 'yellow'}

๐Ÿ“Žwith enumerate

fruit = ["apple", "orange", "banana"]
color = ["red", "orange", "yellow"]
sweety = [30, 10, 1]
 
for i, (f, s) in enumerate(zip(fruit, sweety)):
    print(i, f, s)
    # 0 apple 30
    # 1 orange 10
    # 2 banana 1
  • for๋ฌธ ์•ˆ์˜ zip์œผ๋กœ ๋ฌถ์–ด์ค€ ๋ถ€๋ถ„์˜ ๋ณ€์ˆ˜๋Š” ์†Œ๊ด„ํ˜ธ()๋กœ ๋ฌถ์–ด์ค˜์•ผ ํ•จ ๋ฌถ์ง€ ์•Š๋Š”๋‹ค๋ฉด ํŠœํ”Œํ˜•์‹์œผ๋กœ ์‚ฌ์šฉ z[1], z[2]