切片操作为啥顾头不顾尾?

作者:小K

来源:麦叔编程

刚开始学编程的时候,总觉得切片这个“顾头不顾尾”的设定有点反人类。

为什么不能做到顾头又顾尾呢?

当年初学的时候,输出1~10:

for n in range(1,10):
    print(n)

但是运行输出结果,就只有1~9,然后默默的把10改成了11。

for n in range(1,11):
    print(n)

输出:

1
2
3
4
5
6
7
8
9
10

然后为了在切片时不犯错,总会先在心中默念三遍 「“左开右闭”」

如果你中枪了,请在文章结尾处点赞Mark一下。

「这就非常迷,为什么要这么设计??」

最大的原因

Python、C 和其他语言里都是以 0 作为起始下标的,而人类计数普遍都是从1开始。

好处之一:快速识别元素个数

截取前六个元素操作

lst = [1,2,3,4,5,6,7,8]
print(lst[:6])

输出:

[1, 2, 3, 4, 5, 6]

for循环6次输出 Hello World

for i in range(6):
  print("Hello World!")

输出:

Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!

通过 后下标 - 前下标 得元素个数

lst = [1,2,3,4,5,6,7,8]
print(len(lst[3:6]))

输出:

3

以上例子是不是还蛮“人性化”的?

好处之二:使用任意下标,可分割序列

lst = [1,2,3,4,5,6,7,8]

print(lst[4:])
print(lst[:4])

输出:

[5, 6, 7, 8]
[1, 2, 3, 4]

后记

To denote the subsequence of natural numbers 2, 3, ..., 12 without the pernicious three dots, four conventions are open to us.

表示一个从2,3,...,12的序列,以下四种方式你会选择哪种?

a) 2 ≤ i < 13

b) 1 < i ≤ 12

c) 2 ≤ i ≤ 12

d) 1 < i < 13

选自Edsger W. Dijkstra 的《Why numbering should start at zero》

切片操作为啥顾头不顾尾?

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章