single_min = min([
get_distance(person, hospital)
for i, hospital in enumerate(hospitals)
if visited[i]
])
코드 진짜 깔끔하다..
실제로 enumerate의 작동 방식은 아래와 같다.
# Equivalent to
def enumerate(iterable, start=0):
n = start
for elem in iterable:
yield n, elem # index와 목록의 요소를 동시에 리턴한다.
n += 1
인덱스랑 iterable 요소를 함께 리턴해주는 함수.
그동안 for i in range(n) 혹은 for element in iterable 이런 식으로 썼는데, 이 두 가지를 합친 게 이거구나.
Enumerate 사용 팁
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits, start=1):
print(f"{i} 인덱스 요소는 {fruit} 이다")
# 1 인덱스 요소는 apple이다
# 2 인덱스 요소는 banana이다
# 3 인덱스 요소는 cherry이다
주의해야 할 점은, start index를 설정해줄 뿐이지, 해당 인덱스를 참조하는 게 아니라는 점이다!!