본문 바로가기
Pythonic

[파이썬을 파이썬답게] i번째 원소와 i+1번째 원소

by YGSEO 2021. 3. 8.
728x90

my dirty code

def solution(mylist):
    answer = []
    for i in range(len(mylist)-1):
        answer.append(abs(mylist[i] - mylist[i+1]))
    
    return answer

 

Using zip

def solution(mylist):
    answer = []
    for number1, number2 in zip(mylist, mylist[1:]):
        answer.append(abs(number1 - number2))
    return answer

※ 주의

zip 함수에 서로 길이가 다른 리스트가 인자로 들어오는 경우에는 길이가 짧은 쪽 까지만 이터레이션이 이루어집니다. 더 자세한 내용은 공식 레퍼런스 - zip의 내용을 참고해주세요.

Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted.

 

따라서 mylist[1:] 리스트의 길이가 1짧기 때문에

mylist = [83, 48, 13, 4, 71, 11]

mylist[1:] = [48, 13, 4, 71, 11]

zip 에서 나온 tuple들은

(83, 48)

(48, 13)

...

이런식으로 return

 

728x90

댓글