我过去一直在和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
Python切片使用包含开始索引和独占结束索引。有关详细信息,请参阅docs。所以:
在}的所有元素。在
p[i:j]
中,j
是非包含的:您将选择从i
到{是的,这是正确的行为。从^{} :
相关问题 更多 >
编程相关推荐