从末尾索引列表时,为什么Python从索引-1(而不是0)开始? [英] Why does Python start at index -1 (as opposed to 0) when indexing a list from the end?
问题描述
list = ["a", "b", "c", "d"]
print(list[3]) # Number 3 is "d"
print(list[-4]) # Number -4 is "a"
推荐答案
用另一种方式解释它,因为-0
等于0
,如果从0
开始向后,则它对于解释器来说是模棱两可的.
To explain it in another way, because -0
is equal to 0
, if backward starts from 0
, it is ambiguous to the interpreter.
如果您对-
感到困惑,并且正在寻找另一种更容易理解的向后索引的方法,则可以尝试~
,它是前向的一面镜子:
If you are confused about -
, and looking for another way to index backwards more understandably, you can try ~
, it is a mirror of forward:
arr = ["a", "b", "c", "d"]
print(arr[~0]) # d
print(arr[~1]) # c
~
的典型用法类似于交换镜像节点"或在排序列表中找到中位数":
The typical usages for ~
are like "swap mirror node" or "find median in a sort list":
"""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))
~
实际上是逆代码和补码的数学技巧,在某些情况下更容易理解.
~
actually is a math trick of inverse code and complement code, and it is more easy to understand in some situations.
讨论是否应使用~
之类的python技巧:
Discussion about whether should use python tricks like ~
:
在我看来,如果它是您自己维护的代码,则由于可能具有很高的可读性和可用性,因此您可以使用任何技巧来避免潜在的错误或更轻松地实现目标.但是在团队合作中,避免使用太聪明"的代码,可能会给您的同事带来麻烦.
In my opinion, if it is a code maintained by yourself, you can use any trick to avoid potential bug or achieve goal easier, because of maybe a high readability and usability. But in team work, avoid using 'too clever' code, may bring troubles to your co-workers.
例如,这是 Stefan Pochmann 中的一个简洁代码,用于解决
For example, here is one concise code from Stefan Pochmann to solve this problem. I learned a lot from his code. But some are just for fun, too hackish to use.
# 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技巧.
I have summarized python tricks like this, in case you are interested.
这篇关于从末尾索引列表时,为什么Python从索引-1(而不是0)开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!