基于python3的加密工具-python基础

本文记录 python3 学习的详细过程,实验项目为 基于 python3 的 RSA 加解密工具

基于python3的加密工具博客目录

  1. Python 之禅
  2. 中文声明
  3. 文档注释
  4. 代码注释
  5. 字符集
  6. 转义字符
  7. 输出单个字符
  8. 字符串替换
  9. 占位符
  10. 字符串拼接
  11. 文件读写操作
  12. 列表
  13. 内置list方法。
  14. xrange和range的具体区别
  15. 元组和集合
  16. 字典
  17. 占位符
  18. 文件操作 with
  19. 控制流语句
  20. translate 与 maketrans
    21.* 和 **
  21. 函数
  22. 习题:
  23. lambda
    25.函数参数总结
  24. 删除所有文件

1. Python 之禅


>>> import this
    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!

2. 中文声明


#coding=utf-8
#上面气势随便写都可以,只要符合 coding[:=]\s*([-\w.]+)
#也可以写成-*-coding:utf-8 -*-

3. 文档注释


“这是一个标准模块脚本的写作范式,此处为脚本文档。”  

4. 代码注释


#这里给下面语句做一个注释
new_str = “这是一个全局变量”  

new_str = “这是一个全局变量”  #这里给下面语句做一个注释

"""
这是一个
多行注释
"""

5. 字符集


>>> a = "哈哈哈我是中国人"
>>> len(a)
24

>>> a = u"哈哈哈"
>>> print len(a)

>>> a = "哈哈哈哈"
>>> g = a.deocde('utf-8')
>>> print len(g)
4
>>> len(a)
12

#coding=utf-8
d = "中文".decode('utf-8')
print len(d)

6. 转义字符


>>> a = u"哈哈哈"
>>> a = r"哈哈\n" #不进行转义

7. 输出单个字符


>>> a = "adcde"
>>> print a[0]
>>> len(a)
#查找最后一个字符
>>> a[len(a)-1]
'e'
#查找最后一个字符
>>> a[-1]
'e'
>>> print a[-1]
e
>>> a[0:]
'abcde'
>>> a[0:q]
'a'
>>> a[0:3]
'abc'
>>> a[1:3]
'bc'
>>> print a[:-1]
abcd


>>> a = "123456789"
>>> a[3:5]
'4'
>>> a[3]
'4'
>>> a[6]
'5'

8. 字符串替换


>>> a = "abc"
>>> a.replace('a','ccccccc')
'ccccccc'
>>> print a
abc
>>> d = a.replace('a','cccccc')
>>> id(a)
140135231576824
>>> id(d)
140135231594976

9. 占位符


%s 字符串占位符
%d 数字占位符
    “my name is lilei”
    >>> print "my name is %s lilei" % "hanmeimei's"

    >>> print "my name is %s lilei %s" % ("hanmeimei's", "ten years old")

格式化输出:
    b = "this is {1} {0}" .format("apple","my")
    print b

    b = "this is {whose} {fruit}".format (fruit} = "apple", whose = "my")
    print b

10. 字符串拼接


>>> a = "a"
>>> b = "bcd"
>>> c = "123"
>>> "".join([a,b,c])
'abcd123'
>>> ",".join([a,b,c])
'a,bcd,123'
>>> 

11. 文件读写操作


>>> d = open('a.txt','w')
>>> d.write('hi.\nsecond hi.')
>>> d.close()
>>> d = open('a.txt','r')
>>> help(d)

>>> print d.readline()
hi.
>>> print d.readline()
second hi.
>>> print d.read()
#显示为空

>>> d.seek(0)       #把指针移向开头
>>> print d.read()
hi.
second hi.
>>> 

读取文件
    用open
    用linecache
        help(linecache)  查看源代码

12. 列表


12.1 切片:
    >>> a = [1,2,3,4,5,6,7]
    >>> a[0:4:1]
    [1, 2, 3, 4]
    >>> a[-1:4:1]
    []
    >>> a[-1:4:-1]
    [7, 6]
    >>> a[-1:-4:-1]
    [7, 6, 5]
    >>> a[1:]
    [2, 3, 4, 5, 6, 7]

12.2 添加操作:
    >>> a = [1,2,3]
    >>> b = [4,5,6]
    + 生成一个新的列表
        >>> a + b
        [1, 2, 3, 4, 5, 6]
        >>> id(a)
        140404753217512
    Extend :接受参数并将该参数的每个元素都添加到原有的列表中,原地修改列表而不是新建列表
        >>> a.extend(b)
        >>> a
        [1, 2, 3, 4, 5, 6]
        >>> id(a)
        140404753217512

    Append : 添加任意对象到列表的末端
        >>> a = [1,2,3]
        >>> a.append(4)
        >>> a
        [1, 2, 3, 4]
        >>> a.append([3,4,5])
        >>> a
        [1, 2, 3, 4, [3, 4, 5]]

    Insert : 插入任意对象到列表中,可以控制插入位置。
        >>> a
        [1, 2, 3, 4, [3, 4, 5]]
        >>> a.insert(1,'ab')
        >>> a
        [1, 'ab', 2, 3, 4, [3, 4, 5]]
12.3 修改操作:
    >>> a = [1,2,3]
    >>> a
    [1, 2, 3]
    >>> a[1] = 'python'
    >>> a
    [1, 'python', 3]
12.4 删除操作:
    Del :我们通过索引删除指定位置的元素。
        >>> a = [1,2,3,4,5]
        >>> a
        [1, 2, 3, 4, 5]
        >>> del a[0]
        >>> a
        [2, 3, 4, 5]
    Remove:移除列表中指定值的第一个匹配值。如果没找到的话,会抛异常。
        >>> a
        [2, 3, 4, 5]
        >>> a.remove(4)
        >>> a
        [2, 3, 5]
        >>> a.remove(6)
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        ValueError: list.remove(x): x not in list
    Pop:返回最后一个元素,并从list中删除它。
        >>> a
        [2, 3, 5]
        >>> a.pop()  #返回最后一个元素,并删除
        5
        >>> a
        [2, 3]
12.5 成员关系
    In, not in我们可以判断一个元素是否在列表里。 
    返回一个bool类型,元素在列表里返回true,否则返回fasle.
        >>> a = [1,2,3]
        >>> 2 in a
        True
        >>> 5 in a 
        False
        >>> 5 not in a
        True
12.6 列表推导器
    [expr for iter_var in iterable] 
    1. 首先迭代iterable里所有内容,每一次迭代,都把iterable里相应内容放到iter_var中,再在表达式中应用该iter_var的内容,最后用表达式的计算值生成一个列表。
    比如我们要生成一个包含1到10的列表
    [x for x in range(1,11)]
    Range(1,11)  range(起始位置,结束为止)
        >>> [x for x in range(1,11)]
        [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


    [expr for iter_var in iterable if cond_expr]
    2. 加入了判断语句,只有满足条件的内容才把iterable里相应内容放到iter_var中,再在表达式中应用该iter_var的内容,最后用表达式的计算值生成一个列表。
    要生成包含1到10的所有奇数列表。
    range(1,11,2)   range(起始位置,结束位置,步长)
    [x for x in range(1,11) if x % 2 == 1]
        >>> range(1,11,2)
        [1, 3, 5, 7, 9]
        >>> [x for x in range(1,11,2) if x % 2 == 1]
        [1, 3, 5, 7, 9]

12.7 排序翻转:sort,reverse
    a = [33,11,22,44]


    这个方式直接修改原列表。他的返回值为none,所以

    b = a.sort()
    print b 输出的内容是 None
    我们直接输出a列表变量
        >>> a = [11,33,22,44]
        >>> b = a.sort()
        >>> b
        >>> if b is None:
        ...     print 'haha'
        ... 
        haha
        >>> a
        [11, 22, 33, 44]
    排序:
    a = sorted(sen,key=lambda k:len(k)) 

    list的reverse函数:反转一个list, 他的返回值为none
    比如上面的列表a
    b = a. reverse()
    print b 输出的内容是None
    直接看a列表变量能看到翻转的效果。       
        >>> a
        [11, 22, 33, 44]
        >>> 
        >>> b = a.reverse()
        >>> b
        >>> a
        [44, 33, 22, 11]
    >>> a = [33,11,22,44]
    >>> a.reverse()
    >>> a
    [44, 22, 11, 33]
    >>> a.sort()
    >>> a
    [11, 22, 33, 44]

13. 内置list方法。


a = "asd"
list(a)
返回一个列表,参数是可迭代对象。里面输出的内容还是保持了传入的可迭代对象的元素和顺序。
如果参数为空,则返回一个空的列表                        
    >>> a = "asd"
    >>> list(a)
    ['a', 's', 'd']
    >>> list((1,2))
    [1, 2]
    >>> list()

14. xrange和range的具体区别


>>> a = xrange(1,10)
>>> a
xrange(1, 10)
>>> b = range(1,10)
>>> b
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[0]
1
>>> b[0]
1

14.1 xrange的用法:

    xrange(开始,结束,步长)
    xrange 它生成一个xrange对象。
    比如我们
    a = xrange(1,10)
    print type(a)
    print a[0]
        >>> a = xrange(1,10)
        >>> print type(a)
        <type 'xrange'>
        >>> print a[0]
        1
        >>> print type(b)
        <type 'list'>
        >>> print b[0]
        1
        >>> 

14.2 比较
    range: 直接生成一个列表对象。
    xrange: 它是生成一个xrange对象.
    xrange的用法:
    1当我们需要操作一个非常大的数据,而且内存比较吃紧的时候,我们可以用xrange来操作省内存。
    2xrange一般用在循环里面,比如我们只需要操作部分数据的话,而不是返回全部元素来完成操作,推荐用xrange,效率更高。
    比如:
    for m in range(1000):#[0-999]共一千个数,占用高内存
        if m == 10:
          print 'sss'
          break

    for m in xrange(1000):  #只使用[0-10]共11个数,节省内存开支
        if m == 10:
          print 'sss'
          break

14.3 列表推导式之再应用。

    3.1 可以做很多例子只要你有想法,例

    3.2 取出1-100的所有值的平方。
    [x*x for x in range(100)]
        >>> [x * x for x in range(1,100)]
        [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401, 2500, 2601, 2704, 2809, 2916, 3025, 3136, 3249, 3364, 3481, 3600, 3721, 3844, 3969, 4096, 4225, 4356, 4489, 4624, 4761, 4900, 5041, 5184, 5329, 5476, 5625, 5776, 5929, 6084, 6241, 6400, 6561, 6724, 6889, 7056, 7225, 7396, 7569, 7744, 7921, 8100, 8281, 8464, 8649, 8836, 9025, 9216, 9409, 9604, 9801]

    3.3 里面生成东西不只是数字。

    生成字符串 ['the %s' % d  for d in xrange(10)]
        >>> ["the %s" % d for d in xrange(10)]
        ['the 0', 'the 1', 'the 2', 'the 3', 'the 4', 'the 5', 'the 6', 'the 7', 'the 8', 'the 9']

    生成元组 [(x,y) for x in range(2) for y in range(2)]
        >>> [(x,y) for x in range(2) for y in range(2)]
        [(0, 0), (0, 1), (1, 0), (1, 1)]

    生成字典  举例
    dict([(x,y) for x in range(3) for y in range(2)])
        >>> dict([(x,y) for x in range(3) for y in range(2)])
        {0: 1, 1: 1, 2: 1}

14.4 翻来覆去之再谈引用

    a = ['i','am','lilei']
    b = a
    >>> b
    ['i', 'am', 'lilei']
    >>> id(a)
    140013983516144
    >>> id(b)
    140013983516144
    a[2] = 'laowang'
    >>> a[2] = 'laowang'    #修改a之后,会造成b也跟着变化
    >>> b                   #说明a和b是指向同一个字符串的
    ['i', 'am', 'laowang']  #指针指向是相同的
    >>> a
    ['i', 'am', 'laowang']


    del b
    a #a是什么值
        >>> del b   #仅仅是减少了一次引用,不会删除原字符串
        >>> a
        ['i', 'am', 'laowang']

    5 小技巧之再议删除

    a = []

    1 del a 删除对列表对象的引用(指针)
        >>> a = [1,2,3]
        >>> b = a
        >>> del a
        >>> b
        [1, 2, 3]
    2 del a[:] 清空原列表对象里的元素
        >>> b
        [1, 2, 3]
        >>> c = b
        >>> c
        [1, 2, 3]
        >>> del c[:]
        >>> c
        []
        >>> b
        []
        >>> 

15. 元组和集合


15.1 元组:
    特点:
        1 有序的集合
        2 通过偏移来取数据
        3 属于不可变的对象,不能在原地修改内容,没有排序,修改等操作。
        tuple类型转换
        那为什么有列表还要有元组呢
        元组不可变的好处。保证数据的安全,比如我们传给一个不熟悉的方法或者数据接口,确保方法或者接口不会改变我们的数据从而导致程序问题。
    #! /usr/bin/env python
    #coding=utf-8

    def info(a):
        print 'id %d ' % id(a)
        a[0] = 'haha'
    a = [1,2,3]
    print 'start-'
    print id(a)
    info(a)
    |--------------------------------|
    def info(a):
        print 'id %d ' % id(a)
        a[0] = 'haha'
    a = (1,2,3)     #此处报错,元组是不可改变的
    print 'start-'
    print id(a)
    info(a)
    print a
    |--------------------------------|
    def info(a):
        b = a[:]
        b[0] = 'haha'
        return a
    a = [1,2,3]
    print 'start-'
    print id(a)
    info(a)
    print a
15.2 集合
        集合是没有顺序的概念。所以不能用切片和索引操作。
        1 创建集合。
             可变的:set():
                >>> b = set('abc')
                >>> b
                set(['a', 'c', 'b'])

            不可变的frozenset():#创建之后无法进行修改
                >>> a = frozenset('abc')
                >>> a
                frozenset(['a', 'c', 'b'])
                >>> a.add('2222')
                Traceback (most recent call last):
                  File "<stdin>", line 1, in <module>
                AttributeError: 'frozenset' object has no attribute 'add'
                >>> a.remove('a')
                Traceback (most recent call last):
                  File "<stdin>", line 1, in <module>
                AttributeError: 'frozenset' object has no attribute 'remove'
        2 添加操作: add,update
            >>> b.add('abc')
            >>> b
            set(['a', 'c', 'b', 'abc'])
            >>> b.update('python')
            >>> b
            set(['a', 'c', 'b', 'h', 'o', 'n', 'p', 'abc', 't', 'y'])
        3 删除 remove
            >>> b.remove('abc')
            >>> b
            set(['a', 'c', 'b', 'h', 'o', 'n', 'p', 't', 'y'])
            >>> b.remove(a)
            Traceback (most recent call last):
              File "<stdin>", line 1, in <module>
            KeyError: ()
            >>> b.remove('a')
            >>> b
            set(['c', 'b', 'h', 'o', 'n', 'p', 't', 'y'])
        4 成员关系 in,not in
            >>> d in b
            False
            >>> d not in a
            True
        6 交集,并集,差集 & | -
            >>> a = set('abcd')
            >>> b = set('abcdef')
            >>> a & b
            set(['a', 'c', 'b', 'd'])
            >>> a | b
            set(['a', 'c', 'b', 'e', 'd', 'f'])
            set([])
            >>> b - a
            set(['e', 'f'])
        7 set去重  列表内容元素重复
            >>> a = [1,2,3]
            >>> a.append(1)
            >>> a.append(3)
            >>> a
            [1, 2, 3, 1, 3]
            >>> set(a)
            set([1, 2, 3])
            >>> list(set(a))
            [1, 2, 3]

16. 字典


字典是无序的,它不能通过偏移来存取,只能通过键来存取。
字典 = {'key':value} key:类似我们现实的钥匙,而value则是锁。一个钥匙开一个锁
特点:
    内部没有顺序,通过键来读取内容,可嵌套,方便我们组织多种数据结构,并且可以原地修改里面的内容,属于可变类型。
    组成字典的键必须是不可变的数据类型,比如,数字,字符串,元组等,列表等可变对象不能作为键.
创建字典。{},dict()
    >>> info
    {'a': 1, 'b': 2}
    >>> info['a']
    1
    >>> bjnfo = {'a':[1,2,3],'b':[4,5,6]}
    >>> bjnfo
    {'a': [1, 2, 3], 'b': [4, 5, 6]}
    >>> bjnfo['a'][2] = 5
    >>> bjnfo
    {'a': [1, 2, 5], 'b': [4, 5, 6]}

    >>> binfo = {1:'22',2:'dd'}
    >>> cinfo = {'22':'222','aa':11}
    >>> cinfo
    {'aa': 11, '22': '222'}
    >>> binfo
    {1: '22', 2: 'dd'}
    >>> dinfo = {(1,2,3):'ss',('b','c'):'222'}
    >>> dinfo
    {('b', 'c'): '222', (1, 2, 3): 'ss'}
    >>> finfo = {[1,2,3]:'sss'}
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unhashable type: 'list'
    >>> xinfo = {(1,'2'):'a'}
    >>> xinfo
    {(1, '2'): 'a'}
    >>> xinfo = {(1,'2',[2,3]):'a'}     #列表等可变对象不能作为键
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unhashable type: 'list'

dict()
    >>> ainfo = {'name':'lilei','ago':20}
    >>> ainfo
    {'ago': 20, 'name': 'lilei'}
    >>> binfo = dict(name='liming',age=22)  #使用 dict 添加字典
    >>> binfo
    {'age': 22, 'name': 'liming'}

添加内容 a['xx'] = 'xx'
    >>> ainfo['photo'] = 'iphoto5'  #存在的键是修改操作,不存在的键是添加操作
    >>> ainfo
    {'ago': 20, 'photo': 'iphoto5', 'name': 'lilei'}

修改内容 a['xx'] = 'xx' 
    >>> ainfo['photo'] = 'htc'
    >>> ainfo
    {'ago': 20, 'photo': 'htc', 'name': 'lilei'}

update 参数是一个字典的类型,他会覆盖相同键的值
    >>> binfo.update({'city':'beijing','photo':'nokia'})    # update 会覆盖相同键的值
    >>> binfo
    {'city': 'beijing', 'age': 22, 'name': 'liming', 'photo': 'nokia'}
    >>> binfo.update({'city':'beijing','photo':'sunsing'})
    >>> binfo
    {'city': 'beijing', 'name': 'liming', 'photo': 'sunsing', 'age': 22}

del info['phone'] 删除某个元素
    >>> ainfo = {'age':22,'aa':22}  #删除操作
    >>> ainfo
    {'aa': 22, 'age': 22}
    >>> del ainfo['aa']
    >>> ainfo
    {'age': 22}
    >>> del ainfo
    >>> ainfo
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'ainfo' is not defined

info.clear()删除字典的全部元素
    >>> a = {'info':'22','age':'2'}
    >>> a
    {'info': '22', 'age': '2'}
    >>> a.clear()
    >>> a
    {}

列表和字典的 pop 方法区别:
    1. 字典
        >>> a = {'11':'aa','bb':22}
        >>> a
        {'11': 'aa', 'bb': 22}
        >>> a.pop('bb')
        22
        >>> a
        {'11': 'aa'}
    2. 列表
        >>> binfo = []
        >>> binfo.append('22')
        >>> binfo.append('333')
        >>> binfo
        ['22', '333']
        >>> binfo.pop(0)    #列表下标
        '22'
        >>> binfo
        ['333']
    3. 删除不存在的键名区别
        >>> a = [1,2,3]
        >>> a.pop(4)
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        IndexError: pop index out of range
        >>> 
        >>> b = {'22':'aa','bb':'22'}
        >>> b
        {'bb': '22', '22': 'aa'}
        >>> b.pop('444')
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        KeyError: '444'

        #键名不存在时字典可以指定返回值,列表不可以
        >>> b.pop('444','haha')
        'haha'

 in 和 has_key() 成员关系操作
        >>> a = {'aa':'22','a':'22'}
        >>> a
        {'aa': '22', 'a': '22'}
        >>> 'aa' in a
        True
        >>> 'bbb' in a
        False
        >>> a.has_key('aa')
        True
        >>> a.has_key('aa22')
        False
values() ,keys() ,items()
        keys(): 返回的是列表,里面包含了字典的所有键
        values():返回的是列表,里面包含了字典的所有值
        items:生成一个字典的容器:[()]
        >>> ainfo = {'name':'lilei','ago':20}
        >>> ainfo
        {'ago': 20, 'name': 'lilei'}
        >>> ainfo.keys()
        ['ago', 'name']
        >>> ainfo.values()
        [20, 'lilei']
        >>> ainfo.items()
        [('ago', 20), ('name', 'lilei')]
get:从字典中获得一个值
        >>> ainfo.get('name')
        'lilei'
        >>> ainfo.get('222')
        >>> b = ainfo.get('222')    #键值不存在时,返回值为空
        >>> type(b)
        <type 'NoneType'>
        >>> ainfo.get('222','None') # 返回值为空时可以任意指定返回值
        'None'

复习题:
    循环:生成所有奇数的列表
        >>> b = [45,22,33,25,77,45,98,33,55]
        >>> b
        [45, 22, 33, 25, 77, 45, 98, 33, 55]
        >>> [m for m in b if m % 2 == 1]
        [45, 33, 25, 77, 45, 33, 55]

    输出结果包含45,22
        >>> ["the content %s" % m for m in b[0:2:1]]
        ['the content 45', 'the content 22']

    输出结果是原列表值加2
        >>> [m + 2 for m in b]
        [47, 24, 35, 27, 79, 47, 100, 35, 57]

    用 range 方法和列表推导的方法生成列表:[11,22,33]
        >>> range(11,34,11)
        [11, 22, 33]
        或者:
        >>> [m * 11 for m in range(1,4,1)]
        [11, 22, 33]

    判断4是否在元组里
        >>> a = (1,4,3,5,6,78)
        >>> 4 in a
        True
    将元组里的5改成8
        >>> c = list(a)
        >>> c
        [1, 4, 3, 5, 6, 78]
        >>> c[3] = 8
        >>> c
        [1, 4, 3, 8, 6, 78]
        >>> d = tuple(c)
        >>> d
        (1, 4, 3, 8, 6, 78)

    添加字符串对象'abc'到集合setinfo
        >>> setinfo = set('acbdfemg')
        >>> setinfo
        set(['a', 'c', 'b', 'e', 'd', 'g', 'f', 'm'])
        >>> setinfo.add('abc')
        >>> setinfo
        set(['a', 'c', 'b', 'e', 'd', 'g', 'f', 'm', 'abc'])
    删除集合setinfo里面的成员m
        >>> setinfo.remove('m')
        >>> setinfo
        set(['a', 'c', 'b', 'e', 'd', 'g', 'f', 'abc'])
    求2个集合的交集和并集
        >>> setinfo & finfo
        set(['a', 'b', 'e', 'd', 'g', 'f'])
        >>> setinfo | finfo
        set(['a', 'c', 'b', 'e', 'd', 'g', 'f', 'h', 's', 'abc', 'w', 'r'])

    用字典的方式完成下面一个小型的学生管理系统。


    1 学生有下面几个属性:姓名,年龄,考试分数包括:语文,数学,英语得分。
    比如定义2个同学:
    姓名:李明,年龄25,考试分数:语文80,数学75,英语85
        >>> studentinfo = {'liMing':{'name':'liming','age':25,'fenshu':{'chinese':80,'math':75,'english':85}}}
        >>> studentinfo
        {'liMing': {'fenshu': {'math': 75, 'chinese': 80, 'english': 85}, 'age': 25, 'name': 'liming'}}
    姓名:张强,年龄23,考试分数:语文75,数学82,英语78
        >>> studentinfo['zhangQiang'] = {'name':'zhangqiang','age':23,'fenshu':{'chinese':75,'math':82,'english':78}}
        >>> studentinfo
        {'liMing': {'fenshu': {'math': 75, 'chinese': 80, 'english': 85}, 'age': 25, 'name': 'liming'}, 'zhangQiang': {'fenshu': {'math': 82, 'chinese': 75, 'english': 78}, 'age': 23, 'name': 'zhangqiang'}}
    2 给学生添加一门python课程成绩,李明60分,张强:80分
        >>> studentinfo['liMing']['fenshu']['python'] = 60
        >>> studentinfo['zhangQiang']['fenshu']['python'] = 80
    3 把张强的数学成绩改成89分
        >>> studentinfo['zhangQiang']['fenshu']['math'] = 89
    4 删除李明的年龄数据
        >>> del studentinfo['liMing']['age']
        >>> studentinfo
        {'liMing': {'fenshu': {'python': 60, 'math': 75, 'chinese': 80, 'english': 85}, 'name': 'liming'}, 'zhangQiang': {'fenshu': {'python': 80, 'math': 89, 'chinese': 75, 'english': 78}, 'age': 23, 'name': 'zhangqiang'}}
    5 对张强同学的课程分数按照从低到高排序输出。
        >>> b = studentinfo['zhangQiang']['fenshu'].values()
        >>> b
        [80, 89, 75, 78]
        >>> b.sort()
        >>> b
        [75, 78, 80, 89]
    6 外部删除学生所在的城市属性,不存在返回字符串 None
        >>> studentinfo.pop('city','None')
        'None'

17. 占位符


>>> '%s is a %s' % ('i','boy')
'i is a boy'
>>> '%(who)s is a %(gender)s' % {'who':'i','gender':'boy'}
'i is a boy'

18. 文件操作 with


g = open('a.txt','w')
g.write("ahhahaha\nhahahaha")
g.close()

with open('a.txt','a') as g:
    g.write('xixixixi')

19. 控制流语句


    '''
    :分割了条件和代码块
    缩进了4个空格
    '''
if True:    #条件
    print 4 #执行代码块

x = 3
if x:       #if x == if bool(x)
    print 4

20. translate 与 maketrans


>>> import string
>>> g = string.maketrans('123','abc')
>>> a = '1234567890'
>>> print a.translate(g)
abc4567890
>>> a = '321123132'
>>> print a.translate(g)
cbaabcacb
>>> a.replace('123','abc')
'321abc132'

>>> a = '321123312'
>>> a.translate(g,'1')
'cbbccb'

>>> c = string.maketrans('','')
>>> a.translate(c,'1')
'322332'
>>> a.translate(c,'123')

>>> a.replace('123','')
'321312'

21.* 和 **


    **是字典
    *是元组
def test(*z):
    return z
print test(4,5,3,5,[1,2,6])

def test(*z):
    return z
print test(4,2,3,5)

def test(*z,**kr):
    return z,kr
print test(4,5,3,5,[1,2,6],a=7,b=9,c=8)

结果:
4, 5, 3, 5, [1, 2, 6])
(4, 2, 3, 5)
((4, 5, 3, 5, [1, 2, 6]), {'a': 7, 'c': 8, 'b': 9})

22. 函数


|----------------------------------------------------------|
#coding=utf-8
def add(*num):
#    print type(num)
    d = 0
    for i in num:
        d += i
    return d
print add(1,2,3,4,5)
print add(1,2,3)
print add(2,3,4,5,6,7,8,122,13123,2424,123)     

|----------------------------------------------------------|
def add(num1,num2):
if isinstance(num1,int) and isinstance(num2,int):
    return num1+num2
else:
    return 'error'
    print add('a',(1,2,3))
print add(1,2)
assert add(1,2) == 3
assert add(2,4) == 3
|----------------------------------------------------------|
#递归
def func1(i):
    if i<100:
        return i + func1(i+1)
    return i
print func1(0)

答案:
5050

23. 习题:


#定义一个方法get_doc(module),module参数为该脚本中导入或定义的模块对象,该函数返回module的帮助文档。、
import os
def get_doc(module):
    a = 'pydoc %s' % module
    m = os.popen(a).read()
    return m
print get_doc(urllib)

#定义一个方法func,该func可以引入任意多的字符串参数,结果返回(长度)最长的字符串。
def func(*sen):
    for i in sen:
        if isinstance(i,str):
            pass
        else:
            return "error"
a = sorted(sen,key=lambda k:len(k)) 

24. lambda


lambda之再议:
    1.lambda是一个表达式。
    2.它没有名称,存储的也不是代码块,而是表达式。
    3.它被用作执行很小的功能,不能在里面使用条件语句。

用法:
    d = lambda x:x+1 if x >0 else "error"
    g = lambda x:[(x,i) for i in xrange(0,10)]
    t = [1,2,3,4,5]

    g = filter(lambda x:x > 3,t)

    def e(x):
        return x+1

    print d(1)
    print d(2)
    print d(5)
    print d(-1)
    print d(-2)
    print e(2)
    print g
答案:
    2
    3
    6
    error
    error
    3
    [4, 5]

lambda和filter比较:
    a = [1,2,3,4,5,6]
    b = [1,2,3,4,5,6]
    c = filter(lambda x:x==5,a)
    d = filter(lambda x:x!=5,b)
    print c
    print d
    答案:
    [5]
    [1, 2, 3, 4, 6]

25.函数参数总结


1.位置匹配 func(name)
2.关键字匹配 func(key=value)
3.收集匹配
        1.元组收集 func(name,arg1,arg2)
        2.字典收集 func(name,key1=value1,key1=value2)
4.参数顺序
    先是位置匹配的参数
    再是关键最匹配的参数
    收集匹配的元组参数
    收集匹配的关键字参数


#函数多个参数的顺序问题
    def func(arg1,arg2,arg3):
        return arg1,arg2,arg3
    print func(1,2,3)

    def func1(k1='',k2='',k3=''):
        return k1,k2,k3
    print func1(k3=5,k1=4)

    def func2(a,*kargs,**kwaegs):   #*是元组,**是字典
    return kargs
    print func2(2,3,4,5,6,7,9,[1,2,3,4],{1:2,3:4})

答案:
    (1, 2, 3)
    (4, '', 5)
    (5, 6, 7, 9, [1, 2, 3, 4], {1: 2, 3: 4})

26. 删除所有文件


import os  
import string  
def del_files(dir,topdown=True):  
    for root, dirs, files in os.walk(dir, topdown):  
        for name in files:  
            pathname = os.path.splitext(os.path.join(root, name))  
            if (pathname[1] != ".py" and pathname[1] != ".bak"):  
                os.remove(os.path.join(root, name))  
                print(os.path.join(root,name))  

dir = os.getcwd()  
print(dir)  
del_files(dir)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值