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