Python D1:列表切片

players = ['charles','martina','michael','florence','eli']
print(players)
#获取类表的子集(索引为1-3)
print(players[1:4])#['martina', 'michael', 'florence']
#不指定起始的位置,就会自动从索引为0的地方开放开始
print(players[:4])#['charles', 'martina', 'michael', 'florence']
#不指定终止的位置,就会自动到最后一位结束
print(players[2:])#['michael', 'florence', 'eli']
#返回列表末尾相应距离的元素,可以输出列表末尾的任何切片
print(players[-3:])#['michael', 'florence', 'eli']

#遍历切片
print("<<<<<<<<<<<<<<<<<---------Here are the first three players on my team------------>>>>>>>>>>>>>>>>>>>>>>>")
#遍历某一段切片的前三名队员
for player in players[:3]:
print(player)

#省略起始位置和元素个数,复制一个新的列表,两个列表各不影响

my_foods = ['pizza','falafel','carrot cake']
friend_foods = my_foods[:]
print("my friend's favorite food are:")
print(friend_foods)

my_foods.append('cannoli')
friend_foods.append("tomato")

print(my_foods)
print(friend_foods)

#['pizza', 'falafel', 'carrot cake', 'cannoli']
#['pizza', 'falafel', 'carrot cake', 'tomato']

 

posted @ 2017-09-25 08:45  yyw蔚然  阅读(153)  评论(0编辑  收藏  举报