Python使用列表的一部分

Python使用列表的一部分

在Python中常常用切片来截取一个列表的一部分
1.关于切片, 要创建切片就需要指定切片的起点和终点, 但终点并不会包含在切片内

List_1 = ['charles', 'martina', 'michael', 'florence', 'eli']
print(List_1[0: 3])
print(List_1[1: 4])
print(List_1[: 6])  # 如果没有指定索引的起点则默认从起点开始, 另外, 索引可以超过列表的空间, Python终止于末尾
print(List_1[:])  # 没有指定终点会默认终止于末尾
print(List_1[-3:])  # 索引也可以是负数, 比如指定后三位的切片

2.遍历切片, 可以在for循环中使用切片

List_2 = ['charles', 'martina', 'michael', 'florence', 'eli']
print("Here are the first three players on my team:")
for player in List_2[:3]:
    print(player)

3.利用切片,我们也可以复制列表

List_2 = ['charles', 'martina', 'michael', 'florence', 'eli']
List_3 = List_2  # 这只是给List_2多起了个名字, 没有起到复制列表的作用
# 正确的复制列表是下面的操作
List_4 = List_2[:]

当然,也可以利用切片复制列表的一部分

感谢你的时间

猜你喜欢

转载自blog.csdn.net/m0_46255324/article/details/114099564