zoukankan      html  css  js  c++  java
  • python之常用模块

    导入整个模块

    import 模块名

    导入模块中的某个具体的功能

    from 模块名 import 模块中的方法名(功能)

    import random
    from random import randint

    random 随机模块

    import random
    #取随机小数
    
    print(random.random())                #0~1 之间的随机小数
    print(random.uniform(1,10))           #1~10 之间的随机小数

    取随机整数

    import random
    print(random.randint(0,1))              #0~1之间的整数
    print(random.randrange(0,5))          #0~5之间的整数
    print(random.randrange(0,5,2))       #0~5之间步长为2 的整数

    随机抽取

    l = [1,2,"a",{"k":"v"},(1,2,4)]
    print(random.choice(l))                #随机抽取一个
    print(random.sample(l,3))            #随机抽取n个

    打乱顺序

    import random
    k = [1,2,"ac",{"k","v"},(1,2,3)]
    random.shuffle(k)
    print(k)

    事例: 输出6位纯数字

     
    import random
    def get_code(n=6):
        s = ""
        for i in range(n):
            num = random.randint(0,9)
            s += str(num)
        return s
    print(get_code(6))

    Collections

    1.Counter 计数器

    2.defaultdict 默认值字典

    3.OrderedDict 有序字典

    Counter 计数

     
    from collections import Counter
    print(Counter("凌寒独自开,哈哈哈"))
    
    lst = ["selina","Jerome","Jerry","selina"]
    c = Counter(lst)
    print(c)

    运行结果:

     Counter({'哈': 3, '凌': 1, '寒': 1, '独': 1, '自': 1, '开': 1, ',': 1})
     Counter({'selina': 2, 'Jerome': 1, 'Jerry': 1})

     Process finished with exit code 0

     

    defaultdict 默认值字典

     
    from collections import defaultdict
    selina = defaultdict(lambda:6)        #callable 可调用的, 字典是空的
    print(selina["LL"])           #从字典向外拿数据, 字典是空的, key:callable()
    print(selina["Frank"])         #这里的[] 和get() 不是一回事儿
    print(selina)
    print(selina.get("LL"))

    运行结果:

     6
     6
     defaultdict(<function <lambda> at 0x0000027CAB741E18>, {'ll': 6, 'Frank': 6})
     6

     

    OrderedDict  有序字典

     
    from collections import OrderedDict
    dic = OrderedDict()
    dic["selina"] = "新加坡"
    dic["evelyn"] = "法国"
    print(dic)
    print(dic.get("selina"))
    print(dic.values())
    print(dic["evelyn"])

    运行结果:

     OrderedDict([('selina', '新加坡'), ('evelyn', '法国')])
     新加坡
     odict_values(['新加坡', '法国'])
     法国

    栈Stack(FILO)
    特点: 先进后出

     
     
     1 class StackFullException(Exception):
     2     pass
     3 
     4 class StackEmptyException(Exception):
     5     pass
     6 
     7 class Stack:
     8 
     9     def __init__(self, size):
    10         self.size = size
    11         self.lst = []   # 存放数据的列表
    12         self.top = 0    # 栈顶指针
    13 
    14     # 入栈
    15     def push(self, el):
    16         if self.top >= self.size:
    17             raise StackFullException("your stack is full!!!!!")
    18         self.lst.insert(self.top, el)   # 放元素
    19         self.top += 1   # 栈顶指针向上移动一下
    20 
    21     # 出栈
    22     def pop(self):
    23         if self.top == 0:
    24             raise StackEmptyException("your stack is empty!!!!!")
    25         self.top-=1
    26         el = self.lst[self.top]
    27         return el
    28 s = Stack(4)
    29 s.push('bob')
    30 s.push('jack')
    31 s.push('Peak')
    32 s.push('jary')
    33 print(s.pop())
    34 print(s.pop())
    35 print(s.pop())
    36 print(s.pop())
    37 
    38 
    39 import queue
    40 q= queue.Queue()
    41 q.put('中国')
    42 q.put('法国')
    43 q.put('美国')
    44 print(q.get())
    45 print(q.get())
    46 print(q.get())
    47 
    48 结果
    49 jary
    50 Peak
    51 jack
    52 bob
    53 中国
    54 法国
    55 美国

    队列Queue(FIFO)
    特点: 先进先出

     1 from collections import deque
     2 d = deque()         # 创建双向队列
     3 d.append('娃哈哈')  # 在右侧添加
     4 d.append('QQ星')
     5 d.append('爽歪歪')
     6 d.appendleft('芒果')  # 在左边添加
     7 d.appendleft('榴莲')
     8 d.appendleft('苹果')
     9 print(d.pop())      # 从右边拿数据
    10 print(d.pop())
    11 print(d.pop())
    12 print(d.popleft())  # 从左边拿数据
    13 print(d.popleft())
    14 print(d.popleft())
    15 结果
    16 爽歪歪
    17 QQ星
    18 娃哈哈
    19 苹果
    20 榴莲
    21 芒果

    time时间模块

      1 python程序中,时间一共有三种格式
      2 时间戳时间,float时间(给计算机用的): 1542072130.3895912
      3     英国伦敦 1970-1-1 0:0:0  0时区
      4     北京时间 1970-1-1 8:0:0
      5 结构化时间(tuple时间)
      6 格式化时间,str时间(给用户看的): '2018-11-13 9:21:50'
      7 时间格式转换
      8     时间戳时间 <-结构化时间(tuple时间)-> 格式化时间
      9 
     10 时间格式:
     11 %y 两位数的年份表示(00-99)
     12 %Y 四位数的年份表示(000-9999)
     13 %m 月份(01-12)
     14 %d 月内中的一天(0-31)
     15 %H 24小时制小时数(0-23)
     16 %I 12小时制小时数(01-12)
     17 %M 分钟数(00=59)
     18 %S 秒(00-59)
     19 %a 本地简化星期名称
     20 %A 本地完整星期名称
     21 %b 本地简化的月份名称
     22 %B 本地完整的月份名称
     23 %c 本地相应的日期表示和时间表示
     24 %j 年内的一天(001-366)
     25 %p 本地A.M.或P.M.的等价符
     26 %U 一年中的星期数(00-53)星期天为星期的开始
     27 %w 星期(0-6),星期天为星期的开始
     28 %W 一年中的星期数(00-53)星期一为星期的开始
     29 %x 本地相应的日期表示
     30 %X 本地相应的时间表示
     31 %Z 当前时区的名称
     32 %% %号本身
     33 
     34 
     35 导入时间模块
     36 import time
     37 认识一下三种时间格式
     38 print(time.time())      # 时间戳时间(从1970-01-01 00:00:00开始经过的秒)
     39 print(time.strftime('%Y-%m-%d %H:%M:%S'))  # 格式化时间
     40 print(time.localtime())  # 北京时间(结构化时间)
     41 结果
     42 1545826164.0164113
     43 2018-12-26 20:09:24
     44 time.struct_time(tm_year=2018, tm_mon=12, tm_mday=26, tm_hour=20, tm_min=9, tm_sec=24, tm_wday=2, tm_yday=360, tm_isdst=0)
     45 
     46 print(time.strftime('%c'))
     47 time.gmtime(时间戳)    #UTC时间,与英国伦敦当地时间一致
     48 time.localtime(时间戳) #当地时间,例如我们现在在北京执行这个方法:与UTC时间相差8小时,UTC时间+8小时 = 北京时间
     49 
     50 
     51 结构化时间(python的时间)
     52 print(time.localtime())
     53 t = time.localtime()
     54 print(t.tm_year)
     55 print(t.tm_mon)
     56 print(t.tm_min)
     57 结果
     58 time.struct_time(tm_year=2018, tm_mon=12, tm_mday=26, tm_hour=20, tm_min=23, tm_sec=20, tm_wday=2, tm_yday=360, tm_isdst=0)
     59 2018
     60 12
     61 23
     62 
     63 
     64 时间格式之间的转换问题
     65 格式化时间转换戳时间
     66 #先将格式化时间转换为结构化时间,然后将结构化时间转换为时间戳时间
     67 ret = time.strptime('2008-8-8','%Y-%m-%d')
     68 print(ret)
     69 stmp = time.mktime(ret)
     70 print(stmp)
     71 结果
     72 time.struct_time(tm_year=2008, tm_mon=8, tm_mday=8, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=221, tm_isdst=-1)
     73 1218124800.0
     74 
     75 
     76 时间戳转换格式化时间
     77 先将时间戳转换为结构化时间,然后将结构化看时间转换为格式化时间
     78 ret = time.localtime(1500000000)
     79 print(ret)
     80 str_time = time.strftime('%Y-%m-%d %H:%M:%S',ret)
     81 print(str_time)
     82 结果
     83 time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=10, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0)
     84 2017-07-14 10:40:00
     85 
     86 
     87 1.显示当前时间24小时之前的 年月日 时分秒
     88 方法一 :
     89 计算出1970年到现在经过的秒,然后减去一天的秒,然后转换为格式化时间
     90 t1 = time.time()
     91 print(t1)
     92 t2 = t1 - (60*60*24)
     93 print(t2)
     94 t3 = time.localtime(t2)
     95 print(t3)
     96 t4 = time.strftime('%Y-%m-%d %H:%M:%S',t3)
     97 print(t4)
     98 结果
     99 1545826916.4369211
    100 1545740516.4369211
    101 time.struct_time(tm_year=2018, tm_mon=12, tm_mday=25, tm_hour=20, tm_min=21, tm_sec=56, tm_wday=1, tm_yday=359, tm_isdst=0)
    102 2018-12-25 20:21:56
    103 
    104 方法二
    105 打印结构化时间,然后print进行填充,填充tm_mday天减1
    106 t1 = time.localtime()
    107 print(t1)
    108 print('%s-%s-%s %s:%s:%s'%(
    109 t1.tm_year,
    110 t1.tm_mon,
    111 t1.tm_mday-1,
    112 t1.tm_hour,
    113 t1.tm_min,
    114 t1.tm_sec))
    115 结果
    116 time.struct_time(tm_year=2018, tm_mon=12, tm_mday=26, tm_hour=20, tm_min=13, tm_sec=24, tm_wday=2, tm_yday=360, tm_isdst=0)
    117 2018-12-25 20:13:24
    118 
    119 
    120 2.显示当前月的第一天的0:0:0的时间戳时间
    121 先将时间转化为结构化时间,然后转化为格式化时间
    122 now = time.localtime()
    123 print(now)
    124 str3 = time.strftime('%Y-%m-1 0:0:0',now)
    125 print(str3)
    126 ret2 = time.strptime(str3,'%Y-%m-%d 0:0:0')
    127 print(ret2)
    128 print(time.mktime(ret2))
    129 结果
    130 time.struct_time(tm_year=2018, tm_mon=12, tm_mday=26, tm_hour=20, tm_min=14, tm_sec=16, tm_wday=2, tm_yday=360, tm_isdst=0)
    131 2018-12-1 0:0:0
    132 time.struct_time(tm_year=2018, tm_mon=12, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=335, tm_isdst=-1)
    133 1543593600.0
    134 
    135 方法二
    136 now = time.localtime()
    137 print(now)
    138 str1 = time.strftime('%Y-%m',now)
    139 print(str1)
    140 str2 = time.strptime(str1,'%Y-%m')
    141 print(str2)
    142 print(time.mktime(str2)
    143 结果
    144 time.struct_time(tm_year=2018, tm_mon=12, tm_mday=26, tm_hour=20, tm_min=14, tm_sec=40, tm_wday=2, tm_yday=360, tm_isdst=0)
    145 2018-12
    146 time.struct_time(tm_year=2018, tm_mon=12, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=335, tm_isdst=-1)
    147 1543593600.0

    functools模块
    wraps: 可以改变一个函数的名字,注释...

     1 from functools import wraps
     2 def wrapper(fn):
     3     @wraps(fn)      # 把inner的名字改变成原来的func
     4     def inner(*args,**kwargs):
     5         print('执行前')
     6         ret = fn(*args,**kwargs)
     7         print('执行后')
     8         return ret
     9     return inner
    10 @wrapper        # func = wrapper(func)
    11 def func():
    12     print('bob')
    13 print(func.__name__)
    14 结果
    15 func

    map 映射 reduce 归纳

     1 from functools import reduce
     2 def func(a, b):
     3     return a + b    # 0+1+4+7+2+5+8+3+6+9 累加
     4 ret = reduce(func, [1,4,7,2,5,8,3,6,9])
     5 func(func(func(0, 1),4),7)
     6 print(ret)
     7 print(reduce(lambda x, y:x + y, [i for i in range(101)]))
     8 
     9 执行流程
    10 会把我们每一个数据交给func去执行,把默认值作为第一个参数传递给函数
    11 第二个参数就是你这个序列中的第一个数据
    12 接下来,把刚才返回的结果作为第一个参数传递个a
    13 继续吧刚才的结果给第一个参数,把第三个数据传递给b
    14 
    15 结果
    16 45
    17 5050

    partial偏函数,把函数的参数固定

     1 from functools import partial
     2 def chi(zhushi, fushi):
     3     print(zhushi, fushi)
     4 # 固定函数中某些参数的值
     5 chi2 = partial(chi, fushi="小辣椒")
     6 chi2("大米饭")
     7 chi2("小米饭")
     8 chi2("白米饭")
     9 结果
    10 大米饭 小辣椒
    11 小米饭 小辣椒
    12 白米饭 小辣椒
  • 相关阅读:
    【PAT甲级】1043 Is It a Binary Search Tree (25 分)(判断是否为BST的先序遍历并输出后序遍历)
    Educational Codeforces Round 73 (Rated for Div. 2)F(线段树,扫描线)
    【PAT甲级】1042 Shuffling Machine (20 分)
    【PAT甲级】1041 Be Unique (20 分)(多重集)
    【PAT甲级】1040 Longest Symmetric String (25 分)(cin.getline(s,1007))
    【PAT甲级】1039 Course List for Student (25 分)(vector嵌套于map,段错误原因未知)
    Codeforces Round #588 (Div. 2)E(DFS,思维,__gcd,树)
    2017-3-9 SQL server 数据库
    2017-3-8 学生信息展示习题
    2017-3-5 C#基础 函数--递归
  • 原文地址:https://www.cnblogs.com/q455674496/p/10208673.html
Copyright © 2011-2022 走看看