python中列表的切片操作list[m:n]

如果需要取列表中的某一片段中的值生成一个新的列表,就要用到列表中的切片操作(slice),我们可以使用类似读取列表中元素的语句来完成这个操作,本质上可以把索引值替换成区间值就可以了。具体的表达式可以用 slice = list[m:n] 注意区间的范围用冒号“:”进行分割,它是一个左闭右开区间,也就是从第m+1个元素list[m]开始,到第n个元素之前的一个元素结束(即list[n-1]被遍历,但是list[n]没有被遍历到)。m的默认值,也就是不写的时候,默认是0,n的默认值,默认是最后一个元素的索引+1,也就是len(list)。如果两个都不写,即list[:]可以认为是原来列表的一个拷贝。

print("***********Ex4-10*************")
invited_guests = ['Allan','Bryant','Curry','Duncan','Erving','Fisher']
length = len(invited_guests)
middle = int(length/2)-1
message = "The first three items in the list are:"
print(message)
print(invited_guests[0:3])
message = "Three items from the middle of the list are:"
print(message)
print(invited_guests[middle:middle+3])
message = "The last three items in the list are:"
print(message)
print(invited_guests[-3:])

print("**********Ex4-11**************")
pizzas = ["beef pizza","durian pizza"] #,"cheese pizza","pepperoni"]
friends_pizzas = pizzas[:]
pizzas.append("cheese pizza")
friends_pizzas.append("pepperoni pizza")
for pizza in pizzas:
	print(pizza)
print("************************")

for pizza in friends_pizzas:
	print(pizza)

print("***********Ex4-12*************")

foods = ['pizza','falafel','carrot cake']
my_foods = foods[:]
friend_foods = foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
for food in my_foods:
	print(food)
print("************************")
for food in friend_foods:
	print(food)

输出结果如下:

***********Ex4-10*************
The first three items in the list are:
['Allan', 'Bryant', 'Curry']
Three items from the middle of the list are:
['Curry', 'Duncan', 'Erving']
The last three items in the list are:
['Duncan', 'Erving', 'Fisher']
**********Ex4-11**************
beef pizza
durian pizza
cheese pizza
************************
beef pizza
durian pizza
pepperoni pizza
***********Ex4-12*************
pizza
falafel
carrot cake
cannoli
************************
pizza
falafel
carrot cake
ice cream
[Finished in 0.4s]
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值