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

处理列表的部分元素

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

处理列表的部分元素

处理列表的部分元素 1.切片

要创建切片,可指定要使用的第一个元素的索引和最后一个元素的索引+1。与函数range()一样。
例如:

players = ['a', 'b', 'c', 'd', 'e']
print(players[0:3])

打印结果如下:

['a','b','c']

如果你要提取列表的第2~4个元素,可将起始索引指定
为1,并将终止索引指定为4:

players = ['a', 'b', 'c', 'd', 'e']
print(players[1:4])

打印结果如下:

['b','c','d']

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

players = ['a', 'b', 'c', 'd', 'e']
print(players[:4])

打印结果如下:

['a','b','c','d']

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

players = ['a', 'b', 'c', 'd', 'e']
print(players[2:])

打印结果如下:

['c','d','e']

如果你要输出名单上的最后三个元素,可使用切片players[-3:]:

players = ['a', 'b', 'c', 'd', 'e']
print(players[-3:])

打印结果如下:

['c','d','e']
2.遍历切片

如果要遍历列表的部分元素,可在for循环中使用切片。
例如:

players = ['a', 'b', 'c', 'd', 'e']
print("遍历前三个元素:")
for player in players[:3]:
	print(player.title())

打印结果如下:

A
B
C
3.复制列表

要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:])。这让Python创建一个始于第一个元素,终止于最后一个元素的切片,即复制整个列表。
例如:

my_foods = ['pizza', 'falafel', 'cake']
friend_foods = my_foods[:]
print("My favorite foods are:")
print(my_foods)
print("My friend's favorite foods are:")
print(friend_foods)

打印列表后,我们发现他们包含的结果一样,打印结果如下:

My favorite foods are:
['pizza', 'falafel', 'cake']
My friend's favorite foods are:
['pizza', 'falafel', 'cake']

我们在列表中添加一个元素,并核实每个列表:

my_foods = ['pizza', 'falafel', 'cake']
friend_foods = my_foods[:]
my_foods.append('tea')
friend_foods.append('suger')
print("My favorite foods are:")
print(my_foods)
print("My friend's favorite foods are:")
print(friend_foods)

打印列表后,我们发现他们包含的结果不一样,打印结果如下:

My favorite foods are:
['pizza', 'falafel', 'cake', 'tea']
My friend's favorite foods are:
['pizza', 'falafel', 'cake', 'suger']

注意:这里的friend_foods = my_foods[:]不能写成friend_foods = my_foods,不然这两个变量指同一个列表。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/530021.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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