类切片中的Python列表不起作用

2024-09-30 20:33:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我过去一直在和Python一起工作,现在我很高兴能回来。我试图访问列表中的前两个元素,但我一直只获取第一个元素,而不是第二个元素。在

以下内容来自pythonshell。似乎当我使用[i:j]j=i+1时,我得到的只是第一个元素。这是正确的行为吗?在

>>> p=['ho','he','hoo']
>>> p
['ho', 'he', 'hoo']
>>> p[0:1]
['ho']
>>> p[1:0]
[]
>>> p[0:1]
['ho']
>>> p[1]
'he'
>>> p[0:3]
['ho', 'he', 'hoo']
>>> p[0:2]
['ho', 'he']
 >>> p[0:3]
['ho', 'he', 'hoo']
>>> p[1:2]
['he']

我使用的Python版本是:

Python 3.2 (r32:88445, Feb 21 2011, 21:11:06) [GCC 4.6.0 20110212 (Red Hat 4.6.0-0.7)] on linux2

Linux是Centos,内核是

Linux Fedora 2.6.41.4-1.fc15.x86_64 #1


Tags: 版本元素列表onlinuxhatredfeb
3条回答

Python切片使用包含开始索引和独占结束索引。有关详细信息,请参阅docs。所以:

>>> list = [0, 1, 2, 3, 4]
>>> i = 2
>>> j = 3
>>> # remember that lists are zero based
>>> print list[i:j] # includes 2 and up to, but not 3
[2]
>>> print list[i:j+1] # includes 2 and up to, but not 3+1
[2,3]

p[i:j]中,j是非包含的:您将选择从i到{}的所有元素。在

是的,这是正确的行为。从^{}

The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j.

相关问题 更多 >