发布于2019-08-06 11:10 阅读(1147) 评论(0) 点赞(4) 收藏(3)
Python第四章总结
写第三章总结的时候,由于已经看过一遍了,所以写的时候需要重新再看一遍,但是由于看过了一遍,所以看的就不仔细,所以总结的也没有那么好,从这一章往后,我打算看一点写一点。第四章是接着第三章,讲解列表的,主要是如何遍历列表。
4.1 遍历整个列表
遍历整个列表中的元素,使用的是for循环:
magicians=[‘alice’,‘david’,‘carolina’]
for magician in magicians:
print(magician)
{一定要注意冒号,for循环后面的冒号}
在for循环后面,缩进的都是循环语句的一部分,没有缩进的语句只执行一次。所以,在写程序的时候一定要记得哪些语句需要缩进,哪些不需要缩进。
4.3 创建数值列表
1、函数range()
for number in range(1,5):
print(number){注意:差一打印}
2、使用 range()创建数字列表
要创建数字列表,可使用函数list()将range()的结果直接转换为列表。
numbers = list(range(1,6))
print(numbers)
result:[1, 2, 3, 4, 5]
使用函数range()时,还可指定步长
even_numbers = list(range(2,11,2))
print(even_numbers)
{函数range()从2开始数,然后不断地加2,直到达到或超过终值(11)}
result:[2, 4, 6, 8, 10]
对数字列表执行简单的统计计算:
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
min(digits)
max(digits)
sum(digits)
列表解析:
squares=[value**2 for value in range(1,11)]
print(squares)
列表切片,访问列表的部分元素:
players=[‘charles’,‘martina’,‘michael’,‘florence’,‘eli’]
print(players[0:3]):访问列表的前三个元素
print(players[1:4]):访问列表的234号元素
print(players[:3]):访问前三个元素
print(players[2:]):访问从第三个元素到列表最后的所有元素
print(players[-3:]):访问列表的倒数三个元素
result:
[‘charles’, ‘martina’, ‘michael’]
[‘martina’, ‘michael’, ‘florence’]
[‘charles’, ‘martina’, ‘michael’]
[‘michael’, ‘florence’, ‘eli’]
[‘michael’, ‘florence’, ‘eli’]
遍历切片元素:
for player in players[:3]
复制列表
{要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引( [:])。这让Python创建一个始于第一个元素,终止于最后一个元素的切片,即复制整个列表。}:
my_foods=[‘pizza’,‘falafel’,‘carrot cake’]
friend_foods=my_foods[:]
my_foods.append(‘cannoli’)
friend_foods.append(‘ice cream’)
print(“My favorite foods are:”)
print(my_foods)
print("\nMy friend’s favorite foods are:")
print(friend_foods)
result:
My favorite foods are:
‘pizza’, ‘falafel’, ‘carrot cake’, ‘cannoli’]
My friend’s favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’, ‘ice cream’]
4.5 元组
元素不改变的列表称为元组。
第四章的内容大概就是这样吧,最近会莫名其妙的不开心,不知道为什么。最近特别喜欢听一首歌《像我这样的人》。和在一起舒服的人在一起真的是一件超幸福的事。
作者:放羊人
链接:https://www.pythonheidong.com/blog/article/8184/72b76e883a81a36a5122/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!