本文共 12138 字,大约阅读时间需要 40 分钟。
创建及访问列表
1.列表是有序、可变的数据类型2.列表中可以包含不同类型的对象3.列表可以由[]或工厂函数创建4.支持下标及切片操作
更新列表
1.通过下标只能更新值,不能使用标添加新值>>> alist = [10,35,20,80]>>> alist[-1] = 100>>> alist[1:3] = [30,50,80]2.容器、可变、顺序>>> alist = [10, 80, 20, 60]>>> alist.append(50) # 追加>>> alist.extend([15, 100]) # 将序列对象扩展到alist中>>> alist[10, 80, 20, 60, 50, 15, 100]>>> alist.remove(20) # 删除元素>>> alist.index(60) # 取出60的下标2>>> alist.reverse() # 反转>>> alist.insert(2, 60) # 将60插入到下标为2的位置>>> alist[100, 15, 60, 50, 60, 80, 10]>>> alist.sort() # 升序排列>>> alist.sort(reverse=True) # 降序>>> alist.count(60) # 统计60出现的次数2>>> alist.pop() # 默认弹出最后一项10>>> alist.pop(2) # 弹出下标为2的项目60>>> alist.clear() # 清空列表
列表内建函数
列表方法 | 操作 |
---|---|
list.append(obj) | 向列表中添加-一个对象obj |
list.count(obj) | 返回-一个对象obj在列表中出现的次数 |
list.extend(seq) | 把序列seq的内容添加到列表中 |
list.index(obj) | 返回obj对象的下标 |
list.insert(index, obj) | 在索引量为index的位置插入对象obj |
list.reverse() | 原地翻转列表 |
list.sort() | 排序 |
创建元组
1.通过()或工厂函数tuple()创建元组2.元组是有序的、不可变类型3.与列表类似,作用于列表的操作,绝大数也可以作用于元组
单元素元组
如果一个元组中只有一个元素,那么创建该元组的时候,需要加上一个逗号>>> atuple = ('hello')>>> print(atuple)hello>>> type(atuple)>>> atuple = ('hello',)>>> print(atuple)('hello',)>>> type(atuple) # 练习容器、不可变、顺序>>> atuple = (100, 80, 60, 50, 15)>>> atuple.count(30)0>>> atuple.index(50)3# 单元素元组,必须在结尾加逗号,否则不是元组>>> a = (10)>>> type(a) >>> a10>>> a = (10,)>>> type(a) >>> a(10,)>>> len(a)1
更新元组
虽然元组本身是不可变的,但是因为它同时属于容器类型,也就意味着元组的某一个元素是可变的容器类型,那么这个元素中的项目仍然可变>>> atuple = ('bob', ['boy', 23])>>> atuple[-1]= ['boy', 22]Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment>>> atuple[-1][-1]= 22>>> atuple[-1].append(175)>>> atuple('bob', ['boy', 22, 175])
用列表构建栈结构
1.栈是一个后进先出的结构2.编写一个程序,用列表实现栈结构3.需要支持压栈、出栈、查询功能
方法的返回值
列表等对象,它们的方法就是一个函数。函数有可能有返回值,也可能没有,没有返回值,默认返回None。
>>> alist = [100, 80, 60, 50, 15, 50]>>> a = alist.remove(50)>>> alist[100, 80, 60, 15, 50]>>> print(a)None>>> b = alist.pop() # pop有返回值>>> alist[100, 80, 60, 15]>>> b50
注意:变量没有print()语句,在交互解释器中可以显示它的值,但是作为程序文件运行,没有print()是不会打印值的
1.首先,思考程序的运行方式(0) 压栈(1) 出栈(2) 查询(3) 退出请选择(0/1/2/3): 2[](0) 压栈(1) 出栈(2) 查询(3) 退出请选择(0/1/2/3): 0数据: hello(0) 压栈(1) 出栈(2) 查询(3) 退出请选择(0/1/2/3): 2['hello'](0) 压栈(1) 出栈(2) 查询(3) 退出请选择(0/1/2/3): 1从列表中弹出了: hello(0) 压栈(1) 出栈(2) 查询(3) 退出请选择(0/1/2/3): 2[](0) 压栈(1) 出栈(2) 查询(3) 退出请选择(0/1/2/3): 1空列表(0) 压栈(1) 出栈(2) 查询(3) 退出请选择(0/1/2/3): 3Bye-bye2.分析需要多个功能,将功能写成功能函数def push_it():def pop_it():def view_it():def show_menu():if __name__ == '__main__': show_menu()3.编写主程序代码def push_it(): print('push')def pop_it(): print('pop')def view_it(): print('view')def show_menu(): prompt = '''(0) 压栈(1) 出栈(2) 查询(3) 退出请选择(0/1/2/3):''' while True: choice = input(prompt).strip() if choice not in ['0','1','2','3']: print('无效的输入,请重试') continue if choice == '0': push_it() elif choice == '1': pop_it() elif choice == '2': view_it() else: print('Bye-bye') breakif __name__ == '__main__': show_menu()# 改 ************************************************************stack = []def push_it(): item = input('数据:').strip() if item: stack.append(item)def pop_it(): if stack: print('\033[32;1m从表中弹出:%s\033[0m',stack.pop()) else: print('\033[32;1m空列表\033[0m')def view_it(): print('\033[32;1m%s\033[0m' % stack)def show_menu(): prompt = '''(0) 压栈(1) 出栈(2) 查询(3) 退出请选择(0/1/2/3):''' while True: choice = input(prompt).strip() if choice not in ['0','1','2','3']: print('无效的输入,请重试') continue if choice == '0': push_it() elif choice == '1': pop_it() elif choice == '2': view_it() else: print('Bye-bye') breakif __name__ == '__main__': show_menu()# 改 ************************************************************stack = []def push_it(): item = input('数据:').strip() if item: stack.append(item)def pop_it(): if stack: print('\033[32;1m从表中弹出:%s\033[0m',stack.pop()) else: print('\033[32;1m空列表\033[0m')def view_it(): print('\033[32;1m%s\033[0m' % stack)def show_menu(): # 将函数存到字典中 cmds = { '0':push_it, '1': pop_it,'2':view_it} prompt = '''(0) 压栈(1) 出栈(2) 查询(3) 退出请选择(0/1/2/3):''' while True: choice = input(prompt).strip() if choice not in ['0','1','2','3']: print('无效的输入,请重试') continue if choice == '3': print('Bye-bye') break cmds[choice]() # 在字典中取出函数,进行调用if __name__ == '__main__': show_menu()4.填写函数代码
创建字典
容器、可变、映射
• 通过{ }操作符创建字典 • 通过dict()工厂方法创建字典 • 通过fromkeys()创建具有相同值的默认字典>>> adict = { 'name':'bob', 'age':23}>>> bdict = dict((['name', 'bob'], ['age', 23]))>>> print(bdict){ 'age': 23, 'name': 'bob’}>>> cdict = { }.fromkeys(('bob', 'alice'),23)>>> print(cdict){ 'bob': 23, 'alice': 23}# 练习>>> adict = { 'name': 'bob', 'age': 25}>>> dict(['ab', ('name', 'alice'), ['age', '20']]){ 'a': 'b', 'name': 'alice', 'age': '20'}>>> { }.fromkeys(['bob', 'tom', 'jerry'], 'male'){ 'bob': 'male', 'tom': 'male', 'jerry': 'male'}
访问字典
• 字典是映射类型,意味着它没有下标,访问字典中的值需要使用相应的键>>> for each_key in adict: print 'key=%s, value=%s' % (each_key, adict[each_key])key=age, value=23key=name, value=bob>>> print('%(name)s' % adict)bob# 练习>>> adict{ 'name': 'bob', 'age': 25}>>> 'bob' in adict # bob是字典的key吗?False>>> 'name' in adictTrue>>> for key in adict:... print('%s: %s' % (key, adict[key]))... name: bobage: 25>>> '%(name)s is %(age)s years old.' % adict'bob is 25 years old.'
更新字典
• 通过键更新字典 – 如果字典中有该键,则更新相关值 – 如果字典中没有该键,则向字典中添加新值>>> print adict{ 'age': 23, 'name': 'bob'}>>> adict['age'] = 22>>> print(adict){ 'age': 22, 'name': 'bob'}>>> adict['email'] = 'bob@tarena.com.cn'>>> print adict{ 'age': 22, 'name': 'bob', 'email': 'bob@tarena.com.cn'}# 练习>>> adict{ 'name': 'bob', 'age': 25}>>> adict['email'] = 'bob@tedu.cn'>>> adict{ 'name': 'bob', 'age': 25, 'email': 'bob@tedu.cn'}>>> adict['age'] = 23>>> adict{ 'name': 'bob', 'age': 23, 'email': 'bob@tedu.cn'}
删除字典
• 通过del可以删除字典中的元素或整个字典 • 使用内部方法clear()可以清空字典 • 使用pop()方法可以“弹出”字典中的元素>>> del adict['email’]>>> print(adict){ 'age': 22, 'name': 'bob’}>>> adict.pop('age’)22>>> print(adict){ 'name': 'bob’}>>> adict.clear()>>> print(aDict){ }# 练习• del可以删除可种对象,如删除变量,列表中的某一项、字典中的某一项>>> del adict['email']>>> adict{ 'name': 'bob', 'age': 23}
字典操作符
• 使用字典键查找操作符[ ],查找键所对应的值 • 使用in和not in判断键是否存在于字典中>>> adict = { 'age': 23, 'name': 'bob'}>>> print(adict['name’])Bob>>> 'bob' in adictFalse>>> 'name' in adictTrue
作用于字典的函数
• len():返回字典中元素的数目 • hash():本身不是为字典设计的,但是可以判断某个对象是否可以作为字典的键>>> print(adict){ 'age': 23, 'name': 'bob’}>>> print(len(adict))2>>> hash(3)3>>> hash([])Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'list’# 练习>>> hash(10)10>>> hash('abc')-4683219747325187051>>> hash((1, 2))3713081631934410656>>> hash([1, 2])Traceback (most recent call last): File " ", line 1, in TypeError: unhashable type: 'list'
字典内建方法
• dict.copy():返回字典(深复制)的一个副本>>> print(adict){ 'age': 23, 'name': 'bob'}>>> bdict = adict.copy()>>> bdict['name'] = 'alice’>>> print(adict){ 'age': 23, 'name': 'bob'}>>> print(bdict){ 'age': 23, 'name': 'alice’}
字典内建方法(续1)
• dict.get(key, default=None):对字典dict中的键key,返回它对应的值value,如果字典中不存在此键, 则返回default的值
字典内建方法(续2)
• dict.setdefault(key,default=None):如果字典中 不存在key键,由dict[key]=default为它赋值>>> print(adict){ 'age': 23, 'name': 'bob’}>>> adict.setdefault('age', 20)23>>> print(adict){ 'age': 23, 'name': 'bob’}>>> adict.setdefault('phone', '15033448899’)'15033448899’>>> print(adict){ 'phone': '15033448899', 'age': 23, 'name': 'bob’}
字典内建方法(续3)
• dict.items():返回一个包含字典中(键,值)对元组的 列表 • dict.keys():返回一个包含字典中键的列表 • dict.values():返回一个包含字典中所有值的列表 • dict.update(dict2):将字典dict2的键-值对添加到 字典dict
# 练习>>> adict.get('name')'bob'>>> print(adict.get('qq'))None>>> adict.get('name', 'not found') # 字典中有name,返回val'bob'>>> adict.get('qq', '123456') # 字典中没有qq,返回123456'123456'>>> adict.update({ 'qq': '135265234', 'phone': '1508899007766'})>>> adict{ 'name': 'bob', 'age': 23, 'qq': '135265234', 'phone': '1508899007766'}>>> adict.pop('phone')'1508899007766'>>> adict.keys()dict_keys(['name', 'age', 'qq'])>>> adict.values()dict_values(['bob', 23, '135265234'])>>> adict.items()dict_items([('name', 'bob'), ('age', 23), ('qq', '135265234')])
模拟用户登陆信息系统
1.支持新用户注册,新用户名和密码注册到字典中 2.支持老用户登陆,用户名和密码正确提示登陆成功 3.主程序通过循环询问进行何种操作,根据用户的选择,执行注册或是登陆操作# 练习import getpassuserdb = { }def register(): username = input('username:') if username in userdb: print('用户已存在') else: password = input('password:') userdb[username] = passworddef login(): username = input('username:') password = getpass.getpass('password:') #if username not in userdb or userdb[username] != password: if userdb.get(username) == password: print('登陆成功') else: print('登陆失败')def show_menu(): cmds = { '0': register, '1': login} prompt ='''(0) 注册(1) 登陆(2) 退出请选择(0/1/2): ''' while True: choice = input(prompt).strip() if choice not in ['0','1','2']: print('无效的选择,请重试') continue if choice == '2': print('Bye-bye') break cmds[choice]()if __name__ == '__main__': show_menu()
创建集合
• 数学上,把set称做由不同的元素组成的集合,集合(set)的成员通常被称做集合元素 • 集合对象是一组无序排列的可哈希的值 • 集合有两种类型 – 可变集合set – 不可变集合frozenset>>> s1 = set('hello')>>> s2 = frozenset('hello')>>> s1{ 'l', 'e', 'o', 'h'}>>> s2frozenset({ 'l', 'e', 'o', 'h'})# 练习• 集合是数学上的概念,要求集合中的所有元素都是唯一的。• 集合元素是唯一的、不可变的、无序的。集合就像是一个没有值的字典。>>> aset = set('abc')>>> aset{ 'b', 'a', 'c'}>>> bset = set('bcd')>>> bset{ 'b', 'c', 'd'}>>> aset & bset # 交集{ 'b', 'c'}>>> aset | bset # 并集{ 'c', 'b', 'a', 'd'}>>> aset - bset # 差补,只在aset中包含的元素{ 'a'}>>> bset - aset{ 'd'}
集合类型操作符
• 集合支持用in和not in操作符检查成员 • 能够通过len()检查集合大小 • 能够使用for迭代集合成员 • 不能取切片,没有键>>> len(s1)4>>> for ch in s1: print(ch)leoh
集合类型操作符(续1)
• |:联合,取并集 • &:交集 • -:差补>>> s1 = set('abc')>>> s2 = set('cde')>>> s1 | s2{ 'e', 'd', 'b', 'a', 'c'}>>> s1 & s2{ 'c'}>>> s1 - s2{ 'b', 'a'}
集合的内建方法
• set.add():添加成员 • set.update():批量添加成员 • set.remove():移除成员>>> s1 = set('hello')>>> s1.add('new')>>> s1{ 'h', 'o', 'l', 'e', 'new'}>>> s1.update('new')>>> s1{ 'h', 'o', 'l', 'w', 'e', 'new', 'n'}>>> s1.remove('n')>>> s1{ 'h', 'o', 'l', 'w', 'e', 'new'}# 练习>>> aset.update(['d', 'e'])>>> aset.add('hello')>>> aset.remove('hello')>>> aset{ 'e', 'c', 'b', 'a', 'd'}>>> bset{ 'b', 'c', 'd'}>>> aset.issuperset(bset) # aset是bset的超集吗?True>>> bset.issubset(aset) # bset是aset是aset的子集吗?True>>> aset.union(bset) # aset | bset{ 'c', 'b', 'a', 'd', 'e'}>>> aset.intersection(bset) # aset & bset{ 'b', 'c', 'd'}>>> aset.difference(bset) # aset - bset{ 'a', 'e'}
集合的内建方法(续1)
• s.issubset(t):如果s是t的子集,则返回True,否则返 回False• s.issuperset(t):如果t是s的超集,则返回True,否则 返回False• s.union(t):返回一个新集合,该集合是s和t的并集 • s.intersection(t):返回一个新集合,该集合是s和t的 交集 • s.difference(t):返回一个新集合,该集合是s的成员,但不是t的成员
比较文件内容
1.有两个文件:a.log和b.log 2.两个文件中有大量重复内容 3.取出只有在b.log中存在的行
比较两个文件,将/tmp/mima中存在的,但是在/tmp/passwd中不存在的取出来。
[root@666 ~]# cp /etc/passwd /tmp/[root@666 ~]# cp /etc/passwd /tmp/mima[root@666 ~]# vim /tmp/mima # 修改
>>> with open('/tmp/passwd') as f1:... aset = set(f1)... >>> with open('/tmp/mima') as f2:... bset = set(f2)... >>> cset = bset - aset>>> bset - aset{ 'hello world\n', 'my test\n'}>>> with open('/tmp/diff.txt', 'w') as fobj:... fobj.writelines(cset)
>>> import random>>> nums = [random.randint(1, 10) for i in range(20)]>>> set(nums){ 1, 2, 3, 4, 5, 6, 7, 9, 10}>>> list(set(nums))[1, 2, 3, 4, 5, 6, 7, 9, 10]#################################>>> result = []>>> for i in nums:... if i not in result:... result.append(i)... >>> result[2, 10, 9, 3, 4, 1, 6, 5, 7]
存储 - 标量:数字、字符串 - 容器:列表、元组、字典更新 - 可变:列表、字典 - 不可变:数字、字符串、元组访问 - 直接:数字 - 顺序:字符串、列表、元组 - 映射:字典
转载地址:http://phnwi.baihongyu.com/