rabbits = ['Flopsy', 'Mopsy', 'Cottontail', 'Peter']
current = 0
while current < len(rabbits):
print(rabbits[current])
current += 1
Flopsy Mopsy Cottontail Peter
for rabbit in rabbits:
print(rabbit)
Flopsy Mopsy Cottontail Peter
word = 'cat'
for letter in word:
print(letter)
c a t
accusation = {'room': 'ballroom', 'weapon': 'lead pipe', 'person': 'Col. Mustard'}
for card in accusation:
print(card)
room weapon person
for value in accusation.values():
print(value)
ballroom lead pipe Col. Mustard
for item in accusation.items():
print(item)
(‘room’, ‘ballroom’) (‘weapon’, ‘lead pipe’) (‘person’, ‘Col. Mustard’)
for card, contents in accusation.items():
print('Card', card, 'has the contents', contents)
Card room has the contents ballroom Card weapon has the contents lead pipe Card person has the contents Col. Mustard
4.5.3 break확인 하기: else
cheeses = []
for cheese in cheeses:
print('This shop has some lovely', cheese)
break
else:
print('This is not much of a cheese shop, is it?')
This is not much of a cheese shop, is it?
while문과 마찬가지인for문의else도 뭔가 좀 이상한데,for문을 뭔가 찾는 것으로 생각하고 찾지 못했을 경우else를 호출 된다고 생각하면 쉽다.
cheeses = []
found_one = False
for cheese in cheeses:
found_one = True
print('This shop has some lovely', cheese)
break
if not found_one:
print('This is not much of a cheese shop, is it?')
This is not much of a cheese shop, is it?
4.5.4 여러 시퀀스 순회하기: zip()
** zip() 함수를 사용해서 여러 시퀀스를 병렬로 순회할 수 있다. **
days = ['Monday', 'Tuesday', 'Wednesday']
fruits = ['banana', 'ornage', 'peach']
drinks = ['coffee', 'tea', 'beer']
desserts = ['tiramisu', 'ice cream', 'pie', 'pudding']
for day, fruit, drink, dessert in zip(days, fruits, drinks, desserts):
print(day, ": drink", drink, "- eat", fruit,"- enjoy", dessert)
Monday : drink coffee - eat banana - enjoy tiramisu
Tuesday : drink tea - eat ornage - enjoy ice cream
Wednesday : drink beer - eat peach - enjoy pie
여러 시퀀스중 가장 짧은 시퀀스가 완료되면
zip()은 멈춘다 pudding을 얻을수 없다.english = 'Monday', 'Tuesday', 'Wendesday' french = 'Lundi', 'Mardi', 'Mercredi', 'asdasd'list(zip(english, french))[(‘Monday’, ‘Lundi’), (‘Tuesday’, ‘Mardi’), (‘Wendesday’, ‘Mercredi’)] 두개의 튜플을 만들기 위해
zip()을 사용한다zip()에 의해 반환되는 값은 튜플이나 리스트 자신이 아니라 하나로 반환될 수 있는 순회 가능한 값이다. (asdasd는 없다)dict(zip(english, french)){‘Monday’: ‘Lundi’, ‘Tuesday’: ‘Mardi’, ‘Wendesday’: ‘Mercredi’}
4.5.5 숫자 시퀀스 생성하기: range()
**
range(start, stop, step)**zip()와 같이 순회가능한 객체를 반환 그래서 반복문으로 순회 가능for x in range(0, 3): print(x)0 1 2
list(range(0,3))[0, 1, 2]
for x in range(2, -1, -1): print(x)2 1 0
list(range(2, -1, -1))[2, 1, 0]
list(range(0, 11, 2))[0, 2, 4, 6, 8, 10]
Comments