栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python列表的切片

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python列表的切片

列表切片[开始索引:结束索引]
players = ['charles', 'martina', 'michael', 'florence', 'eli'] 
print(players[0:3])  # => ['charles', 'martina', 'michael'] 
可以生成列表的任何子集,如你要提取列表的第2~4个元素,可将起始索引指定为1,将结束索引指定为4:
players = ['charles', 'martina', 'michael', 'florence', 'eli'] 
print(players[1:4]) #=>['martina', 'michael', 'florence'] 
如果没有指定第一个索引,Python将自动从列表开头开始:
players = ['charles', 'martina', 'michael', 'florence', 'eli'] 
print(players[:4]) #=>['charles', 'martina', 'michael', 'florence']  
要让切片结束于列表末尾,也可使用类似的语法,返回从第3个元素到列表末尾的所有元素:
players = ['charles', 'martina', 'michael', 'florence', 'eli'] 
print(players[2:]) #=>['michael', 'florence', 'eli'] 
负数索引返回离列表末尾相应距离的元素,例如,如果你要输出名单上的最后三名队员,可使用切片players[-3:]:
players = ['charles', 'martina', 'michael', 'florence', 'eli'] 
print(players[-3:]) #=>['michael', 'florence', 'eli'] 
复制列表
players = ['charles', 'martina', 'michael', 'florence', 'eli'] 
player2 = players[:]
print(player2.append('11'))
print(players)  # = >['charles', 'martina', 'michael', 'florence', 'eli'] 
print(player2)  # = >['charles', 'martina', 'michael', 'florence', 'eli', '11']
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/655568.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号