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
'Pythonic' 카테고리의 다른 글
[파이썬을 파이썬답게] sequence 멤버를 하나로 이어붙이기 (0) | 2021.03.08 |
---|---|
[파이썬을 파이썬답게] map 함수 응용하기 (0) | 2021.03.08 |
[파이썬을 파이썬답게] 2차원 리스트 뒤집기 (0) | 2021.03.08 |
[파이썬을 파이썬답게] 알파벳 출력하기 (0) | 2021.03.08 |
[파이썬을 파이썬답게] 문자열 정렬하기 (0) | 2021.03.08 |
댓글