끝부터 목록을 인덱싱 할 때 Python이 인덱스 -1 (0이 아닌)에서 시작하는 이유는 무엇입니까?
이 질문에 이미 답변이 있습니다.
- 슬라이스 표기법 이해하기 32 답변
list = ["a", "b", "c", "d"]
print(list[3]) # Number 3 is "d"
print(list[-4]) # Number -4 is "a"
다른 방식으로 설명하자면 -0은 같기 때문에 0에서 뒤로 시작 0하면 인터프리터에게 모호합니다.
에 대해 혼란스럽고 -더 이해하기 쉽게 역방향 색인을 생성하는 다른 방법을 찾고 있다면을 시도해 볼 수 있습니다 ~. 이것은 순방향의 거울입니다.
arr = ["a", "b", "c", "d"]
print(arr[~0]) # d
print(arr[~1]) # c
에 대한 일반적인 사용법 ~은 "스왑 미러 노드"또는 "정렬 목록에서 중앙값 찾기"와 같습니다.
"""swap mirror node"""
def reverse(arr: List[int]) -> None:
for i in range(len(arr) // 2):
arr[i], arr[~i] = arr[~i], arr[i]
"""find median in a sort list"""
def median(arr: List[float]) -> float:
mid = len(arr) // 2
return (arr[mid] + arr[~mid]) / 2
"""deal with mirror pairs"""
# verify the number is strobogrammatic, strobogrammatic number looks the same when rotated 180 degrees
def is_strobogrammatic(num: str) -> bool:
return all(num[i] + num[~i] in '696 00 11 88' for i in range(len(num) // 2 + 1))
~ 실제로는 역 코드와 보완 코드의 수학 트릭이며 어떤 상황에서는 이해하기가 더 쉽습니다.
다음과 같은 파이썬 트릭을 사용해야하는지 여부에 대한 토론 ~:
제 생각에, 그것이 스스로 관리하는 코드라면, 당신은 잠재적 인 버그를 피하거나 목표를 더 쉽게 달성하기 위해 어떤 트릭을 사용할 수 있습니다. 아마도 높은 가독성과 유용성 때문일 것입니다. 그러나 팀 작업에서 '너무 영리한'코드를 사용하지 않는 것은 동료에게 문제를 일으킬 수 있습니다.
예를 들어 다음은 이 문제 를 해결하기위한 Stefan Pochmann의 간결한 코드입니다 . 나는 그의 코드에서 많은 것을 배웠다. 그러나 일부는 재미로 사용하기에는 너무 엉망입니다.
# a strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down)
# find all strobogrammatic numbers that are of length = n
def findStrobogrammatic(self, n):
nums = n % 2 * list('018') or ['']
while n > 1:
n -= 2
# n < 2 is so genius here
nums = [a + num + b for a, b in '00 11 88 69 96'.split()[n < 2:] for num in nums]
return nums
관심이 있으시면 이와 같은 파이썬 트릭 을 요약했습니다 .
list[-1]
다음에 대한 약어입니다.
list[len(list)-1]
이 len(list)부분은 암시 적입니다. 이것이 -1마지막 요소 인 이유 입니다. 음의 인덱스에 적용됩니다. 뺄셈 len(list)은 항상 암시 적입니다.
이것이 제가 사용하는 니모닉 방법입니다. 그것은 무슨 일이 일어나고 있는지에 대한 접근 방식 일 뿐이지 만 작동합니다.
그것들을 인덱스로 생각하지 마십시오. 순환 목록의 오프셋으로 생각하십시오.
x = [a, b, c, d, e, f, g, h] 목록을 예로 들어 보겠습니다. x [2] 및 x [-2]에 대해 생각해보십시오.
오프셋 0에서 시작합니다. 두 단계 앞으로 나아가면 a에서 b (0에서 1)로, b에서 c (1에서 2)로 이동합니다.
두 단계 뒤로 이동하면 a에서 h (0에서 -1)로 이동 한 다음 h에서 g (-1에서 -2)로 이동합니다.
때문에 -0파이썬은에 0.
함께 0하면 목록의 첫 번째 요소를 얻을
에 -1당신리스트의 마지막 요소를 얻을 수
list = ["a", "b", "c", "d"]
print(list[0]) # "a"
print(list[-1]) # d
list[len(list) - x]x가 뒤에서 요소 위치 인 경우의 속기라고 생각할 수도 있습니다 . 이것은 다음 경우에만 유효합니다.0 < -(-x) < len(list)
print(list[-1]) # d
print(list[len(list) - 1]) # d
print(list[-5]) # list index out of range
print(list[len(list) - 5]) # a
This idiom can be justified using modular arithmetic. We can think of indices as referring to a cell in a list obtained by walking forward i elements. -1 referring to the last element of the list is a natural generalization of this, since we arrive at the last element in the list if we walk backwards one step from the start of the list.
For any list xs and index i positive or negative, the expression
xs[i]
will either have the same value as the expression below or produce an IndexError:
xs[i % len(xs)]
The index of the last element is -1 + len(xs) which is congruent to -1 mod len(xs). For example, in an array of length 12, the canonical index of the last element is 11. 11 is congruent to -1 mod 12.
In Python, though, arrays are more often used as linear data structures than circular ones, so indices larger than -1 + len(xs) or smaller than -len(xs) are out of bounds since there's seldom a need for them and the effects would be really counterintuitive if the size of the array ever changed.
Another explanation:
Your finger points to the first element. The index decides how many places you shift your finger to the right. If the number is negative, you shift your finger to the left.
Of course, you can't step to the left from the first element, so the first step to the left wraps around to the last element.
You could intuitively understand it this way
steps= ["a", "b", "c", "d"]
당신이에서 시작 가정 a에 d, (아직 이동하지 않았기 때문에), A는 당신이 서 당신의 응시 점 (또는 집), 그래서 0으로 표시입니다
한 단계를 b로, 두 번째 단계를 c로 이동하여 세 번째 d에 도달합니다.
그런 다음 d에서 a로 (또는 사무실에서 집으로) 돌아가는 것은 어떻습니까? 당신의 집은 0당신의 가족이 그곳에 살고 있기 때문에 당신의 사무실은 0당신의 마지막 목적지가 될 수 없습니다 .
그래서 집으로 돌아갈 때. d는 집으로 출발하는 마지막 첫 번째 정류장이고, c는 마지막 두 번째 정류장입니다.
'Program Club' 카테고리의 다른 글
| 쿼리 패턴의 구현을 찾을 수 없습니다. (0) | 2020.10.10 |
|---|---|
| MKMapView가 드래그 / 이동되었는지 확인 (0) | 2020.10.10 |
| Groovy의 숨겨진 기능? (0) | 2020.10.10 |
| Python을 사용한 Quicksort (0) | 2020.10.10 |
| .NET Reflector에 대한 "무료"대안이 있습니까? (0) | 2020.10.10 |
