python 学习笔记day05-python字典和集合条件和循环文件和输入输出

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 学习笔记day05-python字典和集合条件和循环文件和输入输出相关的知识,希望对你有一定的参考价值。

字典和集合

    字典基础操作

        创建字典

            通过{}操作符创建字典

            通过dict()工厂函数创建字典

            通过fromkeys()创建具有相同值的默认字典

                >>> aDict = {‘Name‘:‘Bob‘,‘age‘:23}
                >>> import tab
                >>> bDict = dict(([‘name‘,‘bob‘],[‘age‘,23]))
                >>> print bDict
                {‘age‘: 23, ‘name‘: ‘bob‘}
                >>> cDict = {}.fromkeys((‘bob‘,‘alice‘),23)
                >>> print cDict
                {‘bob‘: 23, ‘alice‘: 23}

                >>> dict([‘ab‘,‘cd‘,‘ef‘])
                {‘a‘: ‘b‘, ‘c‘: ‘d‘, ‘e‘: ‘f‘}
                >>> dict([(‘name‘,‘bob‘),(‘age‘,20),[‘qq‘,‘123455‘]])
                {‘qq‘: ‘123455‘, ‘age‘: 20, ‘name‘: ‘bob‘}

        访问字典

            字典是映射类型,意味着它没有下标,访问字典中的值需要使用相应的键

                >>> adict
                {‘age‘: 20, ‘name‘: ‘bob‘}

                >>> for eachKey in adict:
                ...   print "key = %s,value = %s" % (eachKey,adict[eachKey])
                ...
                key = age,value = 20
                key = name,value = bob

                >>> print "%(name)s" %adict
                bob

        更新字典

            通过键更新字典

                - 如果字典中有该键,则更新相关值

                - 如果字典中无该键,则向字典中添加新值

                >>> print adict
                {‘age‘: 20, ‘name‘: ‘bob‘}
                >>> adict[‘age‘] = 22
                >>> print adict
                {‘age‘: 22, ‘name‘: ‘bob‘}
                >>> adict[‘email‘]=‘[email protected]
                >>> print adict
                {‘age‘: 22, ‘name‘: ‘bob‘, ‘email‘: ‘[email protected]

        删除字典

            通过del可以删除字典中的元素或整个字典

            使用内部方法clear()可以清空字典

            使用pop()方法“弹出”字典中的元素

                >>> print adict
                {‘age‘: 22, ‘name‘: ‘bob‘, ‘email‘: ‘[email protected]‘}
                >>> del adict[‘email‘]
                >>> print adict
                {‘age‘: 22, ‘name‘: ‘bob‘}
                >>> adict.pop(‘age‘)
                22
                >>> print adict
                {‘name‘: ‘bob‘}
                >>> adict.clear()
                >>> print adict
                {}

                >>> adict = {‘name‘:‘bob‘,‘age‘:20}
                >>> adict
                {‘age‘: 20, ‘name‘: ‘bob‘}
                >>> adict.popitem()  #随机pop出一个键值,不常用,因为它不接受参数。
                (‘age‘, 20)
                >>> adict
                {‘name‘: ‘bob‘}

                >>> adict.popitem(‘bob‘)
                Traceback (most recent call last):
                  File "<stdin>", line 1, in <module>
                TypeError: popitem() takes no arguments (1 given)

        字典操作符

            使用字典键查找操作符[keyname],查找键所对应的值

            使用in 和not in 判断是否存在于字典中

                >>> adict = {‘name‘:‘bob‘,‘age‘:20}
                >>> print adict[‘name‘]
                bob
                >>> adict
                {‘age‘: 20, ‘name‘: ‘bob‘}
                >>> ‘bob‘ in adict
                False
                >>> ‘name‘in adict
                True

    字典相关函数

        作用于字典的函数

            len():返回字典中元素的数目

            hash():本身不是为字典设计的,但是可以判断某个对象是否可以作为字典的键

                >>> print adict
                {‘age‘: 20, ‘name‘: ‘bob‘}
                >>> print len(adict)
                2

                >>> hash(3)   # 不报错的说明可以作为字典的键,报错则不能作为字典的键
                3
                >>> hash([]) #总结:不可变类型可以作为字典的key,可变的 不行
                Traceback (most recent call last):
                  File "<stdin>", line 1, in <module>
                TypeError: unhashable type: ‘list‘

                >>> hash(‘name‘)
                15034981
                >>> hash((10,20))
                -95038731

        字典内建方法

            dict.copy():返回字典(浅复制(只复制值,id不同))的一个副本

                >>> print adict
                {‘age‘: 20, ‘name‘: ‘bob‘}
                >>> bDict = adict.copy()
                >>> bDict
                {‘age‘: 20, ‘name‘: ‘bob‘}
                >>> bDict[‘name‘] = ‘alice‘
                >>> print bDict
                {‘age‘: 20, ‘name‘: ‘alice‘}
            ####################

                >>> adict
                {‘age‘: 20, ‘name‘: ‘bob‘}
                >>> bdict = adict
                >>> bdict[‘age‘] = 22
                >>> bdict
                {‘age‘: 22, ‘name‘: ‘bob‘}
                >>> adict
                {‘age‘: 22, ‘name‘: ‘bob‘}
            dict.get(key,default=None):对字典dict中的键key,返回它对应的值value,如果字典中不存在此键,则返回default的值

                >>> print adict
                {‘age‘: 22, ‘name‘: ‘bob‘}
                >>> adict.get(‘name‘,‘not found‘)
                ‘bob‘
                >>> adict.get(‘email‘,‘not found‘)
                ‘not found‘

            dict.items(): 返回一个包含字典中(键,值)对元组的列表

            dict.keys():返回一个包含字典中键的列表

                >>> adict.keys()
                [‘qq‘, ‘age‘, ‘name‘]

            dict.values():返回一个包含字典中所有值的列表

                >>> adict.values()
                [‘2222333‘, 22, ‘bob‘]

            dict.update(dict2):将字典dict2的键-值对添加到字典dict

                >>> adict.update({‘phone‘: ‘12345678901‘,‘emali‘: ‘[email protected]‘})
                >>> adict
                {‘qq‘: ‘2222333‘, ‘phone‘: ‘12345678901‘, ‘age‘: 22, ‘name‘: ‘bob‘, ‘emali‘: ‘[email protected]‘}

            dict.setdefault():安全在字典中添加key-value,字典中已存在的key-value不会覆盖

                >>> adict
                {‘age‘: 22, ‘name‘: ‘bob‘}
                >>> adict.setdefault(‘age‘,30)
                22
                >>> adict
                {‘age‘: 22, ‘name‘: ‘bob‘}
                >>> adict.setdefault(‘qq‘,‘2222333‘)
                ‘2222333‘
                >>> adict
                {‘qq‘: ‘2222333‘, ‘age‘: 22, ‘name‘: ‘bob‘}

习题:

    用户登录信息系统

        使用字典模拟一个用户登录信息系统

        1、支持新用户注册,新用户名和密码注册到字典中

        2、支持老用户登录,用户名和密码正确提示登录成功

        3、主程序通过循环询问进行何种操作,根据用户的选择,执行注册或是登录操作

    集合

        集合类型

            数学上,把set称作由不同的元素组成的集合,集合(set)的成员通常被称作集合元素

            集合对象是一组无序排列的可哈希的值

            集合有两种类型

                - 可变集合set

                - 不可变结合 frozenset

                >>> s1 = set(‘hello‘)
                >>> s2 = frozenset(‘hello‘)
                >>> s1
                set([‘h‘, ‘e‘, ‘l‘, ‘o‘])
                >>> s2
                frozenset([‘h‘, ‘e‘, ‘l‘, ‘o‘])

        集合类型操作符

        集合内建方法

本文出自 “linux服务器” 博客,请务必保留此出处http://sailq21.blog.51cto.com/6111337/1859641

以上是关于python 学习笔记day05-python字典和集合条件和循环文件和输入输出的主要内容,如果未能解决你的问题,请参考以下文章

python 学习笔记day05-python字典和集合条件和循环文件和输入输出

day3-python学习笔记

python学习笔记-day2-dict,tuple, string常用函数

python学习笔记-Day8 下 (特殊方法iter方法super方法有序字典实现python单例模式)

Python学习笔记-Day3-set集合操作

python_day2学习笔记