一、列表
1)、什么是列表?如何创建列表?
列表是python中最常见的一种数据类型,使用"[]"中括号将数据括起来,逗号分开
如:list1 = ['physics', 'chemistry', 1997, 2000] list2 = [1, 2, 3, 4, 5 ] list3 = ["a", "b", "c", "d"]
2)、如何访问、修改、增加、删除列表元素?
列表可以使用索引值,列表的第一位元素索引值都是从0开始,将索引值标记为index,访问索引值为index元素即使用list[index],同时也支持倒叙返回,如访问最后一个元素,list[-1]
增加列表元素:1、使用list.apped()内建函数,在元素末尾新增元素
2、使用list.insert()内建方法在特定索引处新增元素
删除列表元素:1、删除特定索引处的元素,使用list.pop(index)内建方法 del list[index] list.remove("具体值") list.clear()清空列表
3)、列表的其他内建方法。计算元素出现次数list.count,复制列表list.copy,查找元素的index索引值list.index,反转列表list.revserse,列表排序list.sort
二、字典
1)、什么叫字典?如何创建字典?
字典是用来存储一对键值对的数据类型,使用大括号括起来,键值对中间使用冒号分割,字典数据是无序的 。如学生成绩表示如下:
score={"tang":90,"jack":100,"john":60}
print(score["tang"]) #打印key为tang的分数
创建字典的3种方法:
#创建一个空字典 empty_dict = dict() print(empty_dict) #用**kwargs可变参数传入关键字创建字典 a = dict(one=1,two=2,three=3) print(a) #传入可迭代对象 b = dict(zip(['one','two','three'],[1,2,3])) print(list(zip(['one','two','three'],[1,2,3]))) print(b) #传入可迭代对象 c = dict([('one', 1), ('two', 2), ('three', 3)]) print(c) c1 = dict([('one', 1), ('two', 2), ('three', 3),('three', 4),('three', 5)]) print(c1)#如果键有重复,其值为最后重复项的值。 #传入映射对象,字典创建字典 d = dict({'one': 1, 'two': 2, 'three': 3}) print(d) print(a == b == c == d)
输出: {} {'one': 1, 'two': 2, 'three': 3} [('one', 1), ('two', 2), ('three', 3)] {'one': 1, 'two': 2, 'three': 3} {'one': 1, 'two': 2, 'three': 3} {'one': 1, 'two': 2, 'three': 5} {'one': 1, 'two': 2, 'three': 3} True
2)、字典元素如何进行新增,修改,删除?
新增字典元素:dict[key]=value,其中可以不存在字典中。给元素设置默认值,若不存在该key时取默认值,如score.setdefault("Tom",99)

修改字典元素:dict[key]=value,,其中key已存在字典中

删除字典元素:使用dict.pop(key)和del dict[key]两种方式来删除

获取字典元素值:可使用dict[key] 和dict.get(key)两种方式来获取。区别:当字典中没有这个key时,get方法不会报错只会报None,而dict[key]会出现报错
