用另一种方式解释,因为-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))
~实际上是逆代码和补码的数学技巧,在某些情况下更容易理解。
讨论是否应该使用python技巧,如~:
在我看来,如果这是一个由你自己维护的代码,你可以使用任何技巧来避免潜在的错误或更容易实现目标,因为它可能具有很高的可读性和可用性。但在团队工作中,避免使用“太聪明”的代码可能会给同事带来麻烦。
例如,这里有一个来自Stefan Pochmann的简洁代码来解决this problem。我从他的密码中学到了很多。但有些只是为了好玩,太老套了。# 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
我把python tricks总结成这样,以防你感兴趣。