Python序列和控制结构
1.1 创建列表
>>> student = ['number','name','age'] >>> student ['number', 'name', 'age'] >>> student = list(('number','name','age')) >>> student ['number', 'name', 'age']
1.2 删除列表
1.2.1 删除整个列表
del
>>> del student[0] >>> student ['name', 'age'] >>> del student >>> student Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> student NameError: name 'student' is not defined
1.2.2 删除列表中首次出现的元素
list.remove()
删除首次出现的0元素:
['c', 'n', ':', '1', '6', '0', '7', '0', 6, 'x', 'student', 'num'] >>> list.remove('0') >>> list ['c', 'n', ':', '1', '6', '7', '0', 6, 'x', 'student', 'num']
1.2.3 删除并返回列表中下标的元素
list.pop()
['c', 'n', ':', '1', '6', '0', '7', '0', 6, 'x', 'student', 'num'] >>> list.pop(0) 'c'
1.3. 增加列表
1.3.1 列表尾部添加元素
>>> list = ['c','n','1','6','0','7','0'] >>> list.append(6) >>> list ['c', 'n', '1', '6', '0', '7', '0', 6] >>> list.append('x') >>> list ['c', 'n', '1', '6', '0', '7', '0', 6, 'x']
1.3.2 列表尾部添加列表
>>> list1 = ['student','num'] >>> list.extend(list1) >>> list ['c', 'n', '1', '6', '0', '7', '0', 6, 'x', 'student', 'num']
1.3.3 指定元素中添加字符
>>> list ['c', 'n', ':', '1', '6', '0', '7', '0', 6, 'x', 'student', 'num'] >>> list.insert(2,':')
1.x. 列表的小用法
1.x.1 某字符出现,次数统计
['c', 'n', ':', '1', '6', '0', '7', '0', 6, 'x', 'student', 'num'] >>> list.count('6') 1
1.x.2 对列表中元素逆向排序
>>> list ['c', 'n', ':', '1', '6', '0', '7', '0', 6, 'x', 'student', 'num'] >>> list.reverse() >>> list ['num', 'student', 'x', 6, '0', '7', '0', '6', '1', ':', 'n', 'c']
1.x.3 升序排序
>>> list ['num', 'student', 'x', 6, '0', '7', '0', '6', '1', ':', 'n', 'c'] >>> >>> list.sort(key=str,reverse=False) >>> list ['0', '0', '1', 6, '6', '7', ':', 'c', 'n', 'num', 'student', 'x']
1.x.4 降序排序
>>> list.sort(key=str,reverse=True) >>> list ['x', 'student', 'num', 'n', 'c', ':', '7', 6, '6', '1', '0', '0']
2.元组
创建元组元组与列表不同,元组一旦创建无法增删改查。代码更加安全,访问速度快
>>> tuple = ('c','n',':',1,6,0,7) >>> tuple ('c', 'n', ':', 1, 6, 0, 7)
3.字典
3.1 创建字典
字典中的键不可以重复。值可以重复
//方法1 中括号直接创建 >>> dic = {'student':'cn','url':'www.baidu.com'} >>> dic {'student': 'cn', 'url': 'www.baidu.com'} //方法2 强制转为字典 >>> student=dict(name='cn',url='www.baidu.com') >>> student {'name': 'cn', 'url': 'www.baidu.com'}
3.2 字典内容的修改
dic[‘键名’]=想改的值
>>> dic = {'name':'xm','age':'21'}
>>> dic['age']=25
>>> dic
{'name': 'xm', 'age': 25}
3.3 字典添加内容
dic[‘新的键名’]=想加的值 直接加即可
>>> dic['sex']='male' >>> dic {'name': 'xm', 'age': 25, 'sex': 'male'}
3.4.返回字典中的所有元素
dict.items()返回字典中所有实例
>>> dic.items() dict_items([('name', 'xm'), ('age', 25), ('sex', 'male')])
3.5. 删除字典中的元素
del dic['想删除的键']或整个字典
>>> del dic['sex'] >>> dic {'name': 'xm', 'age': 25} >>> del dic >>> dic Traceback (most recent call last): File "<pyshell#75>", line 1, in <module> dic NameError: name 'dic' is not defined >>>
4.控制结构
判断结构/循环结构/顺序结构
浙公网安备 33010602011771号