用另一种方式解释,因为-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 技巧,例如~
:
在我看来,如果它是您自己维护的代码,您可以使用任何技巧来避免潜在的错误或更轻松地实现目标,因为可能具有很高的可读性和可用性。但在团队合作中,避免使用“太聪明”的代码,可能会给你的同事带来麻烦。
例如,这是来自的一段简洁代码斯特凡·波赫曼 https://stackoverflow.com/users/1672429/stefan-pochmann解决这个问题 https://leetcode.com/problems/strobogrammatic-number-ii/。我从他的代码中学到了很多东西。但有些只是为了好玩,太老套了,无法使用。
# 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
我总结了蟒蛇技巧 https://github.com/recnac-itna/python_tricks像这样,如果你有兴趣的话。