pythonindex从0开始_当从末尾为列表编制索引时,为什么Python从index-1开始(而不是从0开始)?...

这篇博客探讨了Python中~运算符的用途,它用于实现向后索引,类似于数组的负索引,但更易理解。文章通过代码示例展示了~如何在反转数组元素、查找列表中位数和检查镜像数字等方面发挥作用。作者还提醒,在团队合作中,虽然巧妙的代码可能提高个人代码的可读性,但也可能增加他人理解的难度。文章总结了一些Python小技巧,并提供了适用于个人项目和团队项目的建议。
摘要由CSDN通过智能技术生成

用另一种方式解释,因为-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总结成这样,以防你感兴趣。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值