[python] for문 index-value (인덱스-값) 조회하기 (enumerate, 리스트 최대값 찾기)

for문에서 리스트류를 순환할 때 리스트의 인덱스와 값을 모두 사용해야 하는 경우가 있습니다. 이런 경우 for문에 enumerate 연산자를 활용하면 됩니다. 아래 코드는 한 리스트에서 최대 정수값을 찾아 인덱스와 값을 반환하는 함수입니다.


def get_max(my_list):
    running_max_index = 0
    
    # Iterate over index-value pairs
    for index, item in enumerate(my_list):
        if item >= my_list[running_max_index]:
            running_max_index = index
            
    # Return (index, value) tuple
    return running_max_index, my_list[running_max_index]

print(get_max([1, 3, 5, 4, 2]))


위 코드를 실행하면 (인덱스, 값) 튜플인 (2, 5)가 출력됩니다.


끝.

댓글

이 블로그의 인기 게시물

공압 속도 제어: 미터인 vs 미터아웃

3상 모터 전력에서 전류 계산하기 (How to Convert Three-Phase Power to Amps)

3선 결선식 센서의 타입 PNP, NPN

[PLC] 서보 모터 브레이크 결선, 왜 릴레이 터미널을 써야 할까?

공압회로 기호

제너 다이오드에 저항을 연결하는 이유

[스마트팜] PLC와 프로세스 제어, 그리고 온실 환경제어

[스마트팜] 농업과 수학, 그 특별한 연결고리

[FA] 제어반 회로설계 : Power Circuits External, 필드배선 터미널

[PLC] 접지(지락) 사고와 단락의 차이점 (The Difference Between a Ground Fault and Short Circuit)