Python列表索引

Jus*_*tin -2 python indexing list

我确定这是一个重复的问题,但我不知道如何表达它.蟒蛇[1:3]会产生什么?

pythons = [’Graham’, ’Eric’, ’Terry’, ’John’, ’Michael’, ’Terry’]
Run Code Online (Sandbox Code Playgroud)

我现在知道答案是埃里克和特里,但为什么呢?

Ale*_*ley 5

想想这样:

    #0       #1       #2      #3        #4        #5
[’Graham’, ’Eric’, ’Terry’, ’John’, ’Michael’, ’Terry’]
Run Code Online (Sandbox Code Playgroud)

正如上面所指出的,我们在python中开始计数为0,而我们的范围在顶端不包括在内.所以,当我们说[1:3]时,我们会说"从范围内的索引(1,3)中获取此列表中的所有元素.所以我们将列表分割为这样

          |                 |    
    #0    |   #1       #2   |   #3        #4        #5
[’Graham’,| ’Eric’, ’Terry’,| ’John’, ’Michael’, ’Terry’]
          |                 |
Run Code Online (Sandbox Code Playgroud)

因此,['Eric', 'Terry']返回一个新列表.同样的原则也适用于字符串.