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']
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)