字典和集合

    字典基础操作

        创建字典

            通过{}操作符创建字典

            通过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 "", line 1, in
                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 "", line 1, in
                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'])

        集合类型操作符

            集合支持用in和not in 操作符检查成员

            能够通过len()检查集合大小

            能够使用for迭代集合成员

            不能切片,没有键

                >>> s2
                frozenset(['h', 'e', 'l', 'o'])
                >>> len(s2)
                4
                >>> for ch in s2:
                ...   print ch
                ...
                h
                e
                l
                o

            |:联合,取并集

            &:交集

            -:差补

                >>> s1 = set('abc')
                >>> s2 = set('cde')
                >>> s1 | s2
                set(['a', 'c', 'b', 'e', 'd'])
                >>> s1 & s2
                set(['c'])
                >>> s1 - s2
                set(['a', 'b'])

        集合内建方法

            set.add():添加成员

            set.update():批量添加成员

            set.remove():移除成员

                >>> print s1
                set(['a', 'c', 'b'])
                >>> s1.add('new')
                >>> print s1
                set(['a', 'new', 'c', 'b'])
                >>> s1.update('new')
                >>> print s1
                set(['a', 'c', 'b', 'e', 'n', 'w', 'new'])

                >>> s1.update(['new','world'])
                >>> print s1
                set(['a', 'c', 'b', 'e', 'n', 'world', 'new'])
                >>> s1.remove('n')
                >>> print s1
                set(['a', 'c', 'b', 'e', 'w', 'new'])
            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的成员

                >>> s1 = set('abc')
                >>> s3 = set('abcdef')
                >>> s1
                set(['a', 'c', 'b'])
                >>> s3
                set(['a', 'c', 'b', 'e', 'd', 'f'])
                >>> s1.issubset(s3)
                True
                >>> s3.issuperset(s1)
                True

                >>> s1
                set(['a', 'c', 'b'])
                >>> s2
                set(['c', 'e', 'd'])
                >>> s1.union(s2)
                set(['a', 'c', 'b', 'e', 'd'])
                >>> s1.intersection(s2)
                set(['c'])
                >>> s1.difference(s2)
                set(['a', 'b'])

条件和循环

     if语句

        if基本语法结构

            if判断语句是在python程序中经常用到的句法,其基本语法结构如下

            if expression:

                expr_true_suite

            else:

                expr_false_suite

            如果代码块仅包含一行代码,也可以和前面的写在一行,但是可读性较差,不建议使用

            if expression: expr_true_sutie

        多重条件

            单个if语句可以通过使用布尔操作符and,or和not实现多重判断条件或是否定判断条件

            为了实现更好的可读性,可以使用()分组,但是python并不强制这么做

            if not warn and (system_load >= 10):

                print "Warning: losing resources"

                warn +=1

        elif语句

            检查多个表达式是否为真,并在为真时执行特定代码块中的代码

            没有case或switch语句,可以使用其他数据结构模拟

            if expression1:

                expr1_true_suite

            elif expression2:

                expr2_true_suite

            elif expressioN:

                exprN_true_suite

            else:

                none_of_the_above_suite

习题2:

    模拟case句法

    编写一个程序,模拟case语句功能

    1、提示用户输入执行何种操作(create/delete/modify)

    2、如果输入为create,则打印create user

    3、如果输入为delete,则打印delete user

    4、如果输入为modify,则打印modify user

    5、否则打印input error

        条件表达式

            python 在很长的一段时间里没有条件判断式(C ? X: Y),或称三元运算符,因为范.罗萨姆一直拒绝加入这样的功能

            从Python2.5集成的语法确定为: X if C else Y

                >>> x,y=3,4
                >>> smaller = x if x                >> print smaller
                3

    循环语句

        while语句

            while循环的语法如下:

            while expression:

                suite_to repeat

            通常在当循环次数不确定时使用while循环

        for语句

            for循环会访问一个可迭代对象中的所有元素,并在所有条目都处理过后结束循环,它的语法如下:

            for iter_var in iterable:

                suite_to repeat

            通常在循环次数已知的情况下,会采用for循环

        else 语句

            与其他语言不同,python的while和for语句还支持else语句

            只有循环体正常结束时,else的代码块才会执行

            如果循环体内的代码被中断,那么else代码块也被中断,不会执行

            while expression:

                suite_to_repeat

            else:

                else_clause

        break语句

            break 语句可以结束当前循环,然后跳转到循环以下语句

            可以用在while和for循环中

            一般通过if语句检查,当某个外部条件被触发立即从循环中退出

                >>> while True:
                ...   username = raw_input("username: ")
                ...   if username =='bob':
                ...     break
                ...     
                username: bob
                >>>

        continue语句

            当遇到continue语句时,程序会终止当前循环,并忽略剩余的语句,然后回到循环的顶端

            在开始下一次循环前,如果是条件循环,将验证条件表达式;如果是迭代循环,将验证是否还有元素可以迭代

            只有在验证成功后,才会开始下一次迭代或循环

                >>> for i in range(5):
                ...   if i %2:
                ...     continue
                ...   print i
                ...
                0
                2
                4

        pass语句

            python没有传统的大括号来标记代码块,有时有些地方在语法上要求要有大妈块

            python提供了pass语句,他不做任何事情

                >>> def foo():
                ...
                  File "", line 2
                    
                    ^
                IndentationError: expected an indented block
                >>> def foo():
                ...   pass
                ...

    迭代

        迭代器和iter()函数

            为类序列对象提供了一个类序列的接口

            从根本上说,迭代器就是有一个next()方法的对象

            python的迭代无缝第支持序列对象,而且它还允许程序员迭代非序列类型

            不能向后移动或回到开始,也不能复制一个迭代器。 

                >>> myiter = iter('hello')
                >>> myiter
                
                >>> myiter.next()
                'h'
                >>> myiter.next()
                'e'
                >>> myiter.next()
                'l'
                >>> myiter.next()
                'l'
                >>> myiter.next()
                'o'
                >>> myiter.next()
                Traceback (most recent call last):
                  File "", line 1, in
                StopIteration
                >>> myiter = iter('hello')
                >>> for ch in myiter:
                ...   print ch,
                ...
                h e l l o
            对一个对象调用iter()就可以得到它的迭代器

            当迭代器条目全部取出后会引发一个StopIteration异常,但这并不代表错误发生,只是告诉外部调用者迭代完成

插曲:xrange,range的区别

>>> xrange(100)
xrange(100)
>>> range(100)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]