[Python] ๊ธฐ์ดˆ #8-enumerate

์ •๋ณด๊ตฌ๋‹ˆยท2021๋…„ 12์›” 13์ผ
0

Python

๋ชฉ๋ก ๋ณด๊ธฐ
7/18
post-thumbnail

for ๋ฐ˜๋ณต๋ฌธ : enumerate

๋ฐ˜๋ณต๋ฌธ ์‚ฌ์šฉ ์‹œ ๋ช‡ ๋ฒˆ์งธ ๋ฐ˜๋ณต๋ฌธ์ธ์ง€ ํ™•์ธ์ด ํ•„์š”ํ•  ์ˆ˜ ์žˆ๋‹ค.

์ด๋•Œ enumerate๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด,
์ธ๋ฑ์Šค ๋ฒˆํ˜ธ์™€ ์ปฌ๋ ‰์…˜์˜ ์›์†Œ๋ฅผ tupleํ˜•ํƒœ๋กœ ๋ฐ˜ํ™˜ํ•ด์ค€๋‹ค.

people = [
    {'name': 'bob', 'age': 20},
    {'name': 'carry', 'age': 38},
    {'name': 'john', 'age': 7},
    {'name': 'smith', 'age': 17},
    {'name': 'ben', 'age': 27},
    {'name': 'bobby', 'age': 57},
    {'name': 'red', 'age': 32},
    {'name': 'queen', 'age': 25}
]

for i, person in enumerate(people):
    name = person['name']
    age = person['age']

    print(i,name, age)


# ๊ฒฐ๊ณผ
0 bob 20
1 carry 38
2 john 7
3 smith 17
4 ben 27
5 bobby 57
6 red 32
7 queen 25



ํ™œ์šฉ

enumerate์™€ if์กฐ๊ฑด๋ฌธ์„ ์‚ฌ์šฉํ•ด break๋ฅผ ๋งŒ๋“ค์–ด์ค„ ์ˆ˜ ์žˆ๋‹ค.

people = [
    {'name': 'bob', 'age': 20},
    {'name': 'carry', 'age': 38},
    {'name': 'john', 'age': 7},
    {'name': 'smith', 'age': 17},
    {'name': 'ben', 'age': 27},
    {'name': 'bobby', 'age': 57},
    {'name': 'red', 'age': 32},
    {'name': 'queen', 'age': 25}
]

for i, person in enumerate(people):
    name = person['name']
    age = person['age']
    
    if i > 2 :
    	break
        
    print(i,name, age)
    

# ๊ฒฐ๊ณผ
0 bob 20
1 carry 38
2 john 7
3 smith 17

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