python - 考虑一个列表 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]]
吗?
解决方案
如果您取消嵌套索引操作,可能有助于了解原因:
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
在这种情况下包含相同的数据。
推荐阅读
- javascript - 我的代码在 ReactJs 中给出了“TypeError: Cannot read property 'map' of undefined”
- cassandra - Cassandra:在 ' 处缺少 ')'
试图创建下表:
CREATE TABLE customTableSchema( id UUID PRIMARY KEY, table_id UUID, schema text, created_at timestamp, last_modified_at timesta
- vue.js - 如何在不使用可清除的情况下清除 v-date-picker
- javascript - Telegram html5 游戏返回空白页
- android - 如何在构建并包含为“aar”的 android 应用程序和颤振模块之间进行通信?
- java - 与 Python 在完全相同的代码上相比,Java 超出了时间限制
- python - 根据python中的值溶解多边形
- sql - SQL 两位小数
- google-cloud-platform - 重新启动后无法将远程桌面连接到 Windows 服务器
- python - 在多线程 Python 函数上使用 FastAPI 流式传输视频