# python远足 - tuple取第一个

## 为什么Python从结尾索引列表时从索引-1开始(而不是0)? (5)

``````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))``````

`~` 实际上是反码和补码的数学技巧，在某些情况下更容易理解。

``````# 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 = ["a", "b", "c", "d"]
print(list[3]) # Number 3 is "d"

print(list[-4]) # Number -4 is "a"``````

``steps= ["a", "b", "c", "d"]``

``````list = ["a", "b", "c", "d"]
print(list[0]) # "a"
print(list[-1]) # d``````

``````print(list[-1]) # d
print(list[len(list) - 1]) # d
print(list[-5]) # list index out of range
print(list[len(list) - 5]) # a``````

``xs[i]``

``xs[i % len(xs)]``

``list[-1]``

``list[len(list)-1]``

`len(list)` 部分是隐含的。 这就是为什么 `-1` 是最后一个元素。 这适用于任何负面指数 - `len(list)` 的减法总是隐含的