首页 > 解决方案 > 考虑一个列表 a=["boo",[1,2,3]],为什么 print(a[0:2][0:1]) 打印 ['boo'] 而 print(a[0:2] [0:2]) 打印 ['boo',[1,2,3]]?

问题描述

如果print(a[0:2][0:2])打印['boo',[1,2,3]]
不应该print(a[0:2][0:1])打印[ 'boo' , [1,2]]吗?

标签: pythonlistslice

解决方案


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

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在这种情况下包含相同的数据。


推荐阅读