python 的列表是从0还是1开始的_从末尾索引列表时,为什么Python从索引-1(而不是0)开始?...

1586010002-jmsa.png

list = ["a", "b", "c", "d"]

print(list[3]) # Number 3 is "d"

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

解决方案

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.

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.

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

I have summarized python tricks like this, in case you are interested.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值