Oldboy-Homework-Week2.2

时间:2022-10-10 12:10:08
一、关于Python全栈开发第二周所讲内容的回忆(上篇)
6.列表(list)、元组(tuple)、字典(dictionary)
7.字符串、及其字符串格式化输出
8.for循环
二、详细内容
6.1列表:列表的形式为[1,'a',[i,j]]:
可以存放一些数字、字符串、还有列表本身,与字符串的本质区别就在于:列表可存、可取、可操作性!
6.1.1列表的切片使用:list1 = [1,2,3,4,5,'a','b','c','d']
#顾头不顾尾:list1[1:6]>>>:[1,2,3,4,5,'a']
#冒号后空: list1[4:] >>>:[5,'a','b','c','d']
#冒号前空: list1[:3] >>>:[1,2,3]
#冒号前后空:是复制列表的含义此时:list2 = list1[:] >>>:list2 = [1,2,3,4,5,'a','b','c','d']
#冒号后面为负值:list1[5:-1]>>>:['a','b','c']
#有步距:list1[::2]>>>:[1,3,5,'b','d']
     list1[::-2]>>>:['d','b',5,3,1]这样做意义不大,因为后面我们会学列表的排序和倒转 6.1.2追加

Oldboy-Homework-Week2.2

6.1.3列表的插入:list_name.insert(索引值,插入元素)

Oldboy-Homework-Week2.2

6.1.4统计

Oldboy-Homework-Week2.2

6.1.5删除有三种:①del list[];②list.remove();③list.pop()

①:注意a[索引值]中是列表索引值!且必须为一位不可这样:a[5,6]

Oldboy-Homework-Week2.2

②:注意remove(元素)中是列表里的元素!

Oldboy-Homework-Week2.2

③:注意list.pop(索引值)、list.pop():

默认删除最后一个元素。最重要一点是list.pop()有返回值如下图:

Oldboy-Homework-Week2.2

6.1.6扩展:list.extend(b):

只是将b列表中的元素添加到list表中最后位置,重复元素不进行合并,生硬的添加到表后!

Oldboy-Homework-Week2.2

Oldboy-Homework-Week2.2

6.1.7排序list_name.sort()、倒转list_name.reverse():

注意事项:排序只可以同种类型进行(列表中都是数字或都是字符串),其中字符串按其首字母ACSII码进行排序

Oldboy-Homework-Week2.2

Oldboy-Homework-Week2.2

Oldboy-Homework-Week2.2

Oldboy-Homework-Week2.2

6.1.8索引:获取下标!list_name.index(元素)下标第一位为:0

Oldboy-Homework-Week2.2

6.1.9修改列表内元素:实质就是取出元素并重新赋值

Oldboy-Homework-Week2.2

6.2元组:固定不变的列表:不可以添加、删除、扩展等操作,仅可以统计,索引!

6.3字典:{'key':'value'}

6.3.1.特点:字典里的键值对是无序的,但是键必须唯一!

6.3.2用法:

①增加:

Oldboy-Homework-Week2.2

②删除:

有返回值删除:dict_name.pop()删除指定键和对应的键值对.并返回值

Oldboy-Homework-Week2.2

无返回值删除:del dict_name['key']删除指定键和对应的键值对。

Oldboy-Homework-Week2.2

随机删除:dict_name.popitem():随机删除并且有返回值!

Oldboy-Homework-Week2.2

③查找

判断某元素是否在字典中:必须用键判断,因为键唯一哈

Oldboy-Homework-Week2.2

“查找陌生汉字”的功能:也只能是通过键获取对应值,理由键唯一

Oldboy-Homework-Week2.2

修改已有键的对应值:同增加有关联,增加:键同值不同——是修改!

Oldboy-Homework-Week2.2

④查询键(dict_name.key()),查询值(dict_name.value()),合并字典(dick_name.update())

Oldboy-Homework-Week2.2

Oldboy-Homework-Week2.2

Oldboy-Homework-Week2.2

⑤循环打印字典:也可以只输出i

Oldboy-Homework-Week2.2

Oldboy-Homework-Week2.2

7.字符串、及字符串格式化输出
本篇内容不会总结字符串的后缀用法(就是str.****),会另起篇章详细介绍
用法:string_name = ""和'';还有二者嵌套:statement = "I'm Qinghean";
遵循这样的规则:''' " '' " '''
字符串的格式化输出:
① print("%d%s%f三种类型"%(123,'sdf',123.6))
② 利用字典:print("hello kitty %(name)s is %(age)d"%{'name': 'Qinghean', 'age': 24})
8.for循环:
①for i in X:X处必须是可迭代的序列,如range()、字典、列表等
②for i,v in Y:Y除了满足X要求,还必须是有两个值的:如下示例

Oldboy-Homework-Week2.2

③在for循环中关于enumerate()用法:加序号用的!

Oldboy-Homework-Week2.2

Oldboy-Homework-Week2.2