第四章:操作列表 _4.4使用列表中的一部分野史趣闻

2018-11-01 21:36:53

首先,感谢各位查看‘文章’的朋友,也希望使用python的朋友能够多提意见多留言(目前都是基础还未碰到无法解决的难题,但仍希望朋友提提建议),更希望刚开始学习python的朋友能够持续关注,多多交流,大家共同进步!!!

首次出现问题,需要请教,请看动手试一试中4-10,代码3和4(结果为红色框)。我的问题是:为什么是str(players[1:-1])而不是str(players[1:-2]),因为我想省事直接从后取,请看到的朋友帮忙解答一下,谢谢!!!

言归正传,上码~~~


4.4.1切片

在Python中,我们还可以处理列表的部分元素---python称之为切片。

players = ['charles','martina','michael','florence','eli']
print(players[0:3])
print(players[1:4])
print(players[:4])
print(players[-3:])#输出名单上的最后三名队员

output

4.4.2遍历切片

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

players = ['charles','martina','michael','florence','eli']
print('here are the first three players on my team:')
for player in players[:3]:
print('\t' + player.title())

output

4.4.3复制列表

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

例如, 假设有一个列表, 其中包含你最喜欢的四种食品, 而你还想创建另一个列表, 在其中包含一位朋友喜欢的所有食品。 不过, 你喜欢的食品, 这位朋友都喜欢, 因此你可以通过复制来创建这个列表:

my_foods = ['pizza','falafel','carrot cake']
friend_foods =my_foods[:]
print('my favourite foods are:' + '\n' + str(my_foods))
print('\nmy friends favourite foods are:' +'\n'+ str(friend_foods)

output

为核实我们确实有两个列表, 下面在每个列表中都添加一种食品, 并核实每个列表都记录了相应人员喜欢的食品:

my_foods.append('cannoli')
friend_foods.append('ice cream')
print('\nmy favourite foods are:' + '\n' + str(my_foods))
print('\nmy friends favourite foods are:' +'\n'+ str(friend_foods))

output

Tips:

如果只是简单地将my_foods 赋给friend_foods , 就不能得到两个列表。这种语法实际上是让Python将新变量friend_foods 关联到包含在my_foods 中的列表, 因此这两个变量都指向同一个列表。

动手试一试

4-10 切片 : 选择你在本章编写的一个程序, 在末尾添加几行代码, 以完成如下任务。打印消息“The first three items in the list are:”, 再使用切片来打印列表的前三个元素。打印消息“Three items fromthe middle of the list are:”, 再使用切片来打印列表中间的三个元素。打印消息“The last three items in the list are:”, 再使用切片来打印列表末尾的三个元素。

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

1.print('the first three items in the list are:' + '\n\t' + str(players[:3]))

2.print('three items from the middle of the list are:' + '\n\t' + str(players[1:4]))

3.print('three items from the middle of the list are:' + '\n\t' + str(players[1:-1]))

4.print('the last three items in the list are:' +'\n\t'+ str(players[-3:]))

4-12 使用多个循环 : 在本节中, 为节省篇幅, 程序foods.py的每个版本都没有使用for 循环来打印列表。 请选择一个版本的foods.py, 在其中编写两个for 循环, 将各个食品列表都打印出来。

my_foods = ['pizza','falafel','carrot cake']
friend_foods =my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print('my favorite foods are:')
for my_food in my_foods:
print(my_food)
print('my friend's favorite foods are:')
for friend_food in friend_foods:
print(friend_food)

output

以上便是今晚学习的python的一部分,今天还学了元组的定义和操作,代码明天贴上~~~请帮忙解答问题,谢谢!!!!

本文作者:MozZhang(今日头条)
热门推荐