码迷,mamicode.com
首页 > 编程语言 > 详细

python切片:使用列表的一部分

时间:2020-04-06 17:32:36      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:play   返回   批量   range   HERE   mes   包含   没有   roman   

学习如何处理列表的所有元素。处理列表的部分元素——Python称之为切片。

切片

要创建切片,可指定要使用的第一个元素和最后一个元素的索引。

与函数range()一样,Python在到达指定的第二个索引前面的元素后停止。

要输出列表中的前三个元素,需要指定索引0~3,这将输出分别为012的元素。

下面的示例处理的是一个运动队成员列表:

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])

这一次,切片始于‘marita‘,终于‘florence‘

>>>

[‘martina‘, ‘michael‘, ‘florence‘]

如果没有指定第一个索引,Python将自动从列表开头开始:

players = [‘charles‘, ‘martina‘, ‘michael‘, ‘florence‘, ‘eli‘]

print(players[:4])

由于没有指定起始索引,Python从列表开头开始提取:

>>>

[‘charles‘, ‘martina‘, ‘michael‘, ‘florence‘]

要让切片终止于列表末尾,也可使用类似的语法。

例如,如果要提取从第3个元素到列表末尾的所有元素,可将起始索引指定为2 ,并省略终止索引:

players = [‘charles‘, ‘martina‘, ‘michael‘, ‘florence‘, ‘eli‘]

print(players[2:])

Python将返回从第3个元素到列表末尾的所有元素:

>>>

[‘michael‘, ‘florence‘, ‘eli‘]

无论列表多长,这种语法都能够输出从特定位置到列表末尾的所有元素。

负数索引返回离列表末尾相应距离的元素,因此可以输出列表末尾的任何切片。

例如,如果要输出名单上的最后三名队员,可使用切片players[-3:]

players = [‘charles‘, ‘martina‘, ‘michael‘, ‘florence‘, ‘eli‘]

print(players[-3:])

上述代码打印最后三名队员的名字,即便队员名单的长度发生变化,也依然如此。

>>>

[‘michael‘, ‘florence‘, ‘eli‘]

遍历切片

如果要遍历列表的部分元素,可在for循环中使用切片。在下面的示例中,我们遍历前三名队员,并打印他们的名字:

players = [‘charles‘, ‘martina‘, ‘michael‘, ‘florence‘, ‘eli‘]

print("Here are the first three players on my team:")

for player in players[:3]:

    print(player.title())

代码没有遍历整个队员列表,而只遍历前三名队员:

>>>

Here are the first three players on my team:

Charles

Martina

Michael

在很多情况下,切片都很有用。

编写游戏时,可以在玩家退出游戏时将其最终得分加入到一个列表中。

为获取该玩家的三个最高得分,可以将该列表按降序排列,再创建一个只包含前三个得分的切片。

处理数据时,可使用切片来进行批量处理;

编写Web应用程序时,可使用切片来分页显示信息,并在每页显示数量合适的信息。

players = [‘charles‘, ‘martina‘, ‘michael‘, ‘florence‘, ‘eli‘]

print("Here are the first three players on my team:")

for player in players[:3]:

    print(player.title())

print("Here are the players on my team:")

for player in players:

    print(player.title())

print("Here are the players on my team:")

players=[player.title() for player in players]

for player in players:

    print(player)

print(players[-3:])

>>>

Here are the first three players on my team:

Charles

Martina

Michael

Here are the players on my team:

Charles

Martina

Michael

Florence

Eli

Here are the players on my team:

Charles

Martina

Michael

Florence

Eli

[‘Michael‘, ‘Florence‘, ‘Eli‘]

>>>

 

python切片:使用列表的一部分

标签:play   返回   批量   range   HERE   mes   包含   没有   roman   

原文地址:https://www.cnblogs.com/shwj/p/12642742.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!