[python] enumerate ํ•จ์ˆ˜

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

Python

๋ชฉ๋ก ๋ณด๊ธฐ
8/25
#enumerate()๋Š” '์—ด๊ฑฐํ•˜๋‹ค'๋Š” ๋œป์˜ ํ•จ์ˆ˜๋กœ,
#์—ฌ๋Ÿฌ๊ฐ€์ง€ ์ž๋ฃŒํ˜•(list, tuple, set๋“ฑ)์„
#์ธ๋ฑ์Šค๋ฅผ ํฌํ•จํ•œ enumerate ๊ฐ์ฒด๋กœ return

#list์‚ฌ์šฉ
a = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
for idx, val in enumerate(a):
    print(idx, val)
#์ถœ๋ ฅ
#0 10
#1 9
#2 8
#3 7
#4 6
#5 5
#6 4
#7 3
#8 2
#9 1

#tuple์‚ฌ์šฉ
b = (2, 5, 6)
for idx, val in enumerate(b):
    print(idx, val)
#์ถœ๋ ฅ
#0 2
#1 5
#2 6

#enumerate๊ฐ์ฒด๋ฅผ listํƒ€์ž…์œผ๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ๊ฒฝ์šฐ
letters = ['a', 'b', 'c', 'd']
print(list(enumerate(letters)))
#์ถœ๋ ฅ
#[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

๐Ÿ“’ ์ถ”๊ฐ€ ๊ธฐ๋Šฅ: start ๋งค๊ฐœ๋ณ€์ˆ˜

#์‹œ์ž‘๊ฐ’์„ ์ง€์ • ํ•  ์ˆ˜ ์žˆ์Œ
#default๊ฐ’์€ 0
#์‹œ์ž‘๊ฐ’๋ถ€ํ„ฐ 1์”ฉ ์ฆ๊ฐ€

a = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
for idx, val in enumerate(a, start = 1):
    print(idx, val)
#์ถœ๋ ฅ
#1 10
#2 9
#3 8
#4 7
#5 6
#6 5
#7 4
#8 3
#9 2
#10 1

b = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
for idx, val in enumerate(b, start = 3):
    print(idx, val)
#์ถœ๋ ฅ
#3 10
#4 9
#5 8
#6 7
#7 6
#8 5
#9 4
#10 3
#11 2
#12 1

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