对Python范围和列表索引感到困惑

时间:2015-12-30 14:10:36

标签: python python-2.7 python-3.x

我仍然是python世界中的初学者,其中一个让我转过头来的东西是range内置和列表索引。

我如何知道范围是否会占用最后一个数字?

例如

  • range(15)会算到15或14吗?
  • range(1,15)会算到15或14吗?
  • List_1 [ :15]将计为16(最后一个元素)或休息为15(之前的元素)
  • list_1[1: ]假设列表是16项将计入最后一个元素吗?
  • List_1[1:15]会计算到最后一个元素还是前一个元素?

3 个答案:

答案 0 :(得分:1)

for i in range(15):
    print i #will print out 0..14

for i in range(1, 15):
    print i # will print out 1..14


for i in range (a, b, s):
    print i # will print a..b-1 counting by s. interestingly if while counting by the step 's' you exceed b, it will stop at the last 'reachable' number, example

for i in range(1, 10, 3):
    print i

> 1
> 4
> 7

列表拼接:

a = "hello" # there are 5 characters, so the characters are accessible on indexes 0..4

a[1] = 'e'
a[1:2] = 'e' # because the number after the colon is not reached.

a[x:y] = all characters starting from the character AT index 'x' and ending at the character which is before 'y'

a[x:] = all characters starting from x and to the end of the string

将来,如果你想知道python的行为是什么样的,你可以在python shell中试一试。只需在终端中输入python,你就可以输入你想要的任何行(尽管这对于单行而不是脚本来说非常方便)。

答案 1 :(得分:0)

澄清这种疑虑的最好方法是使用REPL:

>>> range(10)
range(0, 10)
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x = list(range(10))
>>> x[:3]
[0, 1, 2]
>>> x[:1]
[0]
>>> x[1:10]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

答案 2 :(得分:0)

嗯,这是以前答案的散文版本

  1. range(15)实际上会生成一个索引从0到14的列表
  2. range(0, 15)做同样的事;除了指定了起始和结束索引
  3. list[:14]访问list的内容,包括第14个索引(第15个元素)
  4. list[1:]从第一个索引(第二个元素)访问list的内容,直到(并包括)最后一个元素