zoukankan      html  css  js  c++  java
  • day04

    1.divmod(x,y)获取一个整数x除以y的商和余数

    ret = divmod(101, 10)
    print(ret)

    2.获取随机验证码

    import random
    l = []
    for i in range(0, 6):
        t = random.randrange(0, 5)
        if t == 1 or t == 3:
            num = random.randrange(0, 10)
            l.append(str(num))
        else:
            temp = random.randrange(65, 91)
            word = chr(temp)
            l.append(word)
    ret = ''.join(l)
    print(ret)

     3.isinstance 用于判断对象是否某个类的实例

    s = 'alex'
    r = isinstance(s,str)
    print(r)

    4.filter 和 map

    filter参数为一个函数和一个可迭代对象,做筛选,如为真返回结果

    def f1(a):
        if a > 22:
            return True
    l = [11,22,33,44,55]
    ret = filter(f1,l)
    print(list(ret))

    l = [11, 22, 33, 44, 55]
    ret = filter(lambda a: a > 22, l)
    print(list(ret))

    map参数为一个函数和一个可迭代对象,对迭代对象的每个元素做函数操作,然后返回操作后的结果

    l = [11, 22, 33, 44, 55]
    def f1(a):
        return a + 100
    ret = map(f1,l)
    print(list(ret))

    lambda表达式

    l = [11, 22, 33, 44, 55]
    ret = map(lambda a: a + 100, l)
    print(list(ret))

    5.装饰器

    功能:

    1.自动执行outer函数,并且将其下边的函数f1当做参数传递给outer函数

    2.将outer函数的返回值重新复制给f1

    直白一点说就是:一旦一个函数被装饰器装饰,原函数会被重新赋值,值为装饰器的内层函数

    def outer(func):
        def inner():
            print('before')
            func()
            print('after')
        return inner
    
    
    @outer
    def f1():
        print('F1')

    带参数和返回值的,完整的装饰器

    def outer(func):
        def inner(*args, **kwargs):
            print('before')
            r = func(*args, **kwargs)
            print('after')
            return r
        return inner
    
    
    @outer
    def f1(args):
        print(args)
        return '我是f1'
    
    
    @outer
    def f2(a1,a2):
        print(a1,a2)
        return '我是F2'

    双层装饰器:(嵌套)

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    USER_INFO = {'is_login': False}
    
    
    def check_login(func):
        def inner(*args, **kwargs):
            if USER_INFO.get('is_login'):
                ret = func(*args, **kwargs)
                return ret
            else:
                print('请登陆')
        return inner
    
    
    def check_admin(func):
        def inner(*args, **kwargs):
            if USER_INFO.get('user_type') == 2:
                ret = func(*args, **kwargs)
                return ret
            else:
                print('权限不够')
        return inner
    
    
    @check_login
    @check_admin
    def home():
        print('home')
    
    
    @check_admin
    def index():
        print('Index')
    
    
    def login():
        user = input('请输入账号:')
        if user == 'admin':
            USER_INFO['is_login'] = True
            USER_INFO['user_type'] = 2
        else:
            USER_INFO['is_login'] = True
            USER_INFO['user_type'] = 1
    
    
    def main():
        while True:
            inp = input('1,登陆2,查看内容,3,超级管理员权限
    >>>')
            if inp == '1':
                login()
            elif inp == '2':
                home()
            elif inp == '3':
                index()
    
    
    main()

    6.字符串格式化

    (1)% 占位符

    s = '我的名字是%s年龄是%d' %('terry',20)
    print(s)
    s1 = '我的名字是%(name)s年龄是%(age)d' % {'name': 'terry', 'age': 20}
    print(s1)

    %.2f 小数点后保留2位

    print('一斤西瓜%.2f元' % 2.3)

    几种常用方法

    t1 = 'i am %s ' % "alex"
    t2 = 'i am %s age %d' % ('alex', 20)
    t3 = 'i am %(name)s age %(age)d' % {'name': 'alex', 'age': 20}
    t4 = 'percent %.2f' % 99.9675
    t5 = 'i am %(pp).2f' % {'pp': 12.334355}
    t6 = 'i am %.2f %%' % 12.343532

    (2)s.format

    [[fill]align][sign][#][0][width][,][.precision][type]

    • fill           【可选】空白处填充的字符
    • align        【可选】对齐方式(需配合width使用)
      • <,内容左对齐
      • >,内容右对齐(默认)
      • =,内容右对齐,将符号放置在填充字符的左侧,且只对数字类型有效。 即使:符号+填充物+数字
      • ^,内容居中
    • sign         【可选】有无符号数字
      • +,正号加正,负号加负;
      •  -,正号不变,负号加负;
      • 空格 ,正号空格,负号加负;
    • #            【可选】对于二进制、八进制、十六进制,如果加上#,会显示 0b/0o/0x,否则不显示
    • ,            【可选】为数字添加分隔符,如:1,000,000
    • width       【可选】格式化位所占宽度
    • .precision 【可选】小数位保留精度
    • type         【可选】格式化类型
      • 传入” 字符串类型 “的参数
        • s,格式化字符串类型数据
        • 空白,未指定类型,则默认是None,同s
      • 传入“ 整数类型 ”的参数
        • b,将10进制整数自动转换成2进制表示然后格式化
        • c,将10进制整数自动转换为其对应的unicode字符
        • d,十进制整数
        • o,将10进制整数自动转换成8进制表示然后格式化;
        • x,将10进制整数自动转换成16进制表示然后格式化(小写x)
        • X,将10进制整数自动转换成16进制表示然后格式化(大写X)
      • 传入“ 浮点型或小数类型 ”的参数
        • e, 转换为科学计数法(小写e)表示,然后格式化;
        • E, 转换为科学计数法(大写E)表示,然后格式化;
        • f , 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
        • F, 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
        • g, 自动在e和f中切换
        • G, 自动在E和F中切换
        • %,显示百分比(默认显示小数点后6位)

     常用格式化:

    tpl = "i am {}, age {}, {}".format("seven", 18, 'alex')
      
    tpl = "i am {}, age {}, {}".format(*["seven", 18, 'alex'])
      
    tpl = "i am {0}, age {1}, really {0}".format("seven", 18)
      
    tpl = "i am {0}, age {1}, really {0}".format(*["seven", 18])
      
    tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18)
      
    tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18})
      
    tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])
      
    tpl = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1)
      
    tpl = "i am {:s}, age {:d}".format(*["seven", 18])
      
    tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18)
      
    tpl = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18})
     
    tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
     
    tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
     
    tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)
     
    tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)
    

    7.迭代器

    迭代器是访问集合元素的一种方式。迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退,不过这也没什么,因为人们很少在迭代途中往后退。另外,迭代器的一大优点是不要求事先准备好整个迭代过程中所有的元素。迭代器仅仅在迭代到某个元素时才计算该元素,而在这之前或之后,元素可以不存在或者被销毁。这个特点使得它特别适合用于遍历一些巨大的或是无限的集合,比如几个G的文件

    特点:

    1. 访问者不需要关心迭代器内部的结构,仅需通过next()方法不断去取下一个内容
    2. 不能随机访问集合中的某个值 ,只能从头到尾依次访问
    3. 访问到一半时不能往回退
    4. 便于循环比较大的数据集合,节省内存
    >>> a = iter([1,2,3,4,5])
    >>> a
    <list_iterator object at 0x101402630>
    >>> a.__next__()
    1
    >>> a.__next__()
    2
    >>> a.__next__()
    3
    >>> a.__next__()
    4
    >>> a.__next__()
    5
    >>> a.__next__()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    StopIteration
    

    8.生成器

    一个函数调用时返回一个迭代器,那这个函数就叫做生成器(generator);如果函数中包含yield语法,那这个函数就会变成生成器;

    def func():
        yield 1
        yield 2
        yield 3
        yield 4
    

    上述代码中:func是函数称为生成器,当执行此函数func()时会得到一个迭代器。

    >>> temp = func()
    >>> temp.__next__()
    1
    >>> temp.__next__()
    2
    >>> temp.__next__()
    3
    >>> temp.__next__()
    4
    >>> temp.__next__()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    StopIteration
    

    实例:利用生成器自定义range

    def nrange(num):
        temp = -1
        while True:
            temp = temp + 1
            if temp >= num:
                return
            else:
                yield temp
    

    9.时间模块,date 和datetime

    时间相关的操作,时间有三种表示方式:

    • 时间戳               1970年1月1日之后的秒,即:time.time()
    • 格式化的字符串    2014-11-11 11:11,    即:time.strftime('%Y-%m-%d')
    • 结构化时间          元组包含了:年、日、星期等... time.struct_time    即:time.localtime()
    print time.time()
    print time.mktime(time.localtime())
       
    print time.gmtime()    #可加时间戳参数
    print time.localtime() #可加时间戳参数
    print time.strptime('2014-11-11', '%Y-%m-%d')
       
    print time.strftime('%Y-%m-%d') #默认当前时间
    print time.strftime('%Y-%m-%d',time.localtime()) #默认当前时间
    print time.asctime()
    print time.asctime(time.localtime())
    print time.ctime(time.time())
       
    import datetime
    '''
    datetime.date:表示日期的类。常用的属性有year, month, day
    datetime.time:表示时间的类。常用的属性有hour, minute, second, microsecond
    datetime.datetime:表示日期时间
    datetime.timedelta:表示时间间隔,即两个时间点之间的长度
    timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
    strftime("%Y-%m-%d")
    '''
    import datetime
    print datetime.datetime.now()
    print datetime.datetime.now() - datetime.timedelta(days=5)
        %Y  Year with century as a decimal number.
        %m  Month as a decimal number [01,12].
        %d  Day of the month as a decimal number [01,31].
        %H  Hour (24-hour clock) as a decimal number [00,23].
        %M  Minute as a decimal number [00,59].
        %S  Second as a decimal number [00,61].
        %z  Time zone offset from UTC.
        %a  Locale's abbreviated weekday name.
        %A  Locale's full weekday name.
        %b  Locale's abbreviated month name.
        %B  Locale's full month name.
        %c  Locale's appropriate date and time representation.
        %I  Hour (12-hour clock) as a decimal number [01,12].
        %p  Locale's equivalent of either AM or PM.

     10.日志模块 logging

    老师给的模板,可以直接用

    #! /usr/bin/env python
    # -*- coding: utf-8 -*-
    # __author__ = "Q1mi"
    
    """
    logging配置
    """
    
    import os
    import logging
    import logging.config
    import logging.handlers
    
    
    standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' 
                      '[%(levelname)s][%(message)s]'
    
    simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
    
    id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'
    
    LOGGING_DIC = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'standard': {
                'format': standard_format
            },
            'simple': {
                'format': simple_format
            },
        },
        'filters': {},
        'handlers': {
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',  # 打印到屏幕
                'formatter': 'simple'
            },
            'default': {
                'level': 'DEBUG',
                'class': 'logging.handlers.RotatingFileHandler',    # 保存到文件
                'filename': os.path.join("{}/log".format(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'all.log'),
                'maxBytes': 1024*1024*5,  # 5M
                'backupCount': 5,
                'formatter': 'standard',
            },
        },
        'loggers': {
            '': {
                'handlers': ['default', 'console'],
                'level': 'DEBUG',
                'propagate': True,
            },
        },
    }
    logging.config.dictConfig(LOGGING_DIC)
    logger = logging.getLogger(__name__)
    logger.info('It works')

    使用方法:

    import time
    import logging
    from log_demo import MyLogging  # 导入自定义的logging配置
    
    logger = logging.getLogger(__file__)  # 生成logger实例
    
    
    def demo():
        logger.debug("start range... time:{}".format(time.time()))
        for i in range(10):
            logger.debug("i:{}".format(i))
            time.sleep(2)
        else:
            logger.debug("over range... time:{}".format(time.time()))
    
    if __name__ == "__main__":
        demo()
    

      

  • 相关阅读:
    [转]asp.net页面缓存技术
    UL和LI在div中的高度的IE6下兼容性
    jquery制作的横向图片滚动带横向滚动条TackerScroll
    电脑可以上网,但是qq登陆不上去?
    Introduction to discrete event system学习笔记4.6
    Introduction to Discrete event system学习笔记4.9
    Introduction to discrete event systemsstudy 4.5
    Symbolic synthesis of obserability requirements for diagnosability B.Bittner,M.Bozzano,A.Cimatti,and X.Olive笔记4.16
    Introduction to discrete event system学习笔记4.8pm
    Introduction to discrete event system学习笔记 4.8
  • 原文地址:https://www.cnblogs.com/terrycy/p/5793493.html
Copyright © 2011-2022 走看看