Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 考虑到列表a=[“boo”、[1,2,3]],为什么打印(a[0:2][0:1])打印[&&x27;boo&&x27;],而打印(a[0:2][0:2])打印[&&x27;boo&&x27;[1,2,3]?_Python_List_Slice - Fatal编程技术网

Python 考虑到列表a=[“boo”、[1,2,3]],为什么打印(a[0:2][0:1])打印[&&x27;boo&&x27;],而打印(a[0:2][0:2])打印[&&x27;boo&&x27;[1,2,3]?

Python 考虑到列表a=[“boo”、[1,2,3]],为什么打印(a[0:2][0:1])打印[&&x27;boo&&x27;],而打印(a[0:2][0:2])打印[&&x27;boo&&x27;[1,2,3]?,python,list,slice,Python,List,Slice,如果打印(a[0:2][0:2])打印['boo',[1,2,3]]? 不应该print(a[0:2][0:1])print['boo',[1,2]]?这里a[0:2]告诉索引范围[1,2]中的所有元素,因此这将创建一个子列表 sublist = ['boo', [1, 2, 3]] 及 a[0:2][0:1]这说明在子列表中再次出现元素索引范围形式为[0,1]的子列表,即['boo']如果取消索引操作,可能有助于了解原因: a = ['boo', [1, 2, 3]] b = a[0:2

如果
打印(a[0:2][0:2])
打印
['boo',[1,2,3]]


不应该
print(a[0:2][0:1])
print
['boo',[1,2]]

这里
a[0:2]
告诉索引范围[1,2]中的所有元素,因此这将创建一个子列表

sublist = ['boo', [1, 2, 3]] 


a[0:2][0:1]
这说明在子列表中再次出现元素索引范围形式为[0,1]的子列表,即
['boo']

如果取消索引操作,可能有助于了解原因:

a = ['boo', [1, 2, 3]] 
b = a[0:2] # this creates a new list from `a` with elements 0 and 1
b[0] # 'boo'
b[1] # [1, 2, 3]
f = b[0:1] # before this, b is the same as ['boo', [1, 2, 3]]
           # retrieving only the first element [0, 1], returns a new list:
f[0] # 'boo'
f # ['foo'] (a list with just 'foo')
创建与前面列表内容相同的列表(
[0:2]
)时,会产生不同的结果:

c = a[0:2] # this creates a new list from `a` with elements 0 and 1
c[0] # 'boo'
c[1] # [1, 2, 3]
c[0:2] # the same as a[0:2][0:2], which is the same as just `c` as well.    

a
c
在本例中包含相同的数据。

Python中列表切片的工作方式如下:
当您在列表
a=[“boo”,[1,2,3]
上执行
a[0:2][0:1]
时,首先执行
a[0:2]
,这将为您提供一个包含从位置0到1的元素的结果列表
=>
[“boo”,[1,2,3]

接下来,对该结果执行
[0:1]
,它返回的列表中只有位于0位置的元素,即
[“boo”]


当执行列表上的
a[0:2][0:2]
时,
a=[“boo”、[1,2,3]
,首先得到位置0和1=>
[“boo”、[1,2,3]]
,然后再次请求位置0和1上的元素(
[0:2]
),这正是
[“boo”、[1,2,3]]

您应该了解Python的索引机制。