Language/Python
[Python] enumerate()를 활용한 index, value 동시 접근
Junhong Kim
2018. 3. 29. 17:58
728x90
반응형
index로 value 접근
아래 방법으로 index를 통해 value 에 접근할 수 있지만 권장하지 않습니다.
arr = ['a', 'b', 'c'] for index in range(len(arr)): print(index, arr[index])
# Output:
# 0 a
# 1 b
# 2 c
enumerate()를 활용한 index와 value 동시 접근
python 내장 함수인
enumerate()
내장 함수를 사용하면 index와 value 에 동시 접근할 수 있습니다.
arr = ['a', 'b', 'c'] for index, value in enumerate(arr): print(index, value)
# Output:
# 0 a
# 1 b
# 2 c
enumerate() 활용
순서가 있는 자료형(tuple, list, string)을 첫번째로 인자로 받아서, 각각 index와 value를 enumerate 객체로 리턴합니다.
arr = ['a', 'b', 'c'] value_index = list(enumerate(arr)) print(value_index)
# output:
# [(0, 'a'), (1, 'b'), (2, 'c')]
두번째 인자로 정수를 전달하면 시작하는 index 값을 조정할 수 있습니다.
arr = ['a', 'b', 'c'] value_index = list(enumerate(arr, 2)) print(value_index)
# output:
# [(2, 'a'), (3, 'b'), (4, 'c')]
728x90
반응형