Python基础入门(10)- 常用函数与高阶函数

1.加密工具

1.1.hashlib模块介绍

hashlib加密后难破解,且不可逆


1.2.hashlib模块中的常用方法

Python基础入门(10)- 常用函数与高阶函数

Python基础入门(10)- 常用函数与高阶函数

 1 # coding:utf-8
 2 
 3 import hashlib
 4 import time
 5 
 6 base_sign='用户名'
 7 
 8 #客户端
 9 def custom():
10     a_timestamp=int(time.time())
11     _token='%s%s' % (base_sign,a_timestamp)
12     hashobj=hashlib.sha1(_token.encode('utf-8'))
13     a_token=hashobj.hexdigest()
14     return a_token,a_timestamp
15 
16 #服务器
17 def service_check(token,timestamp):
18     # time.sleep(1)
19     _token='%s%s' % (base_sign,int(time.time()))
20     b_token=hashlib.sha1(_token.encode('utf-8')).hexdigest()
21     if token==b_token:
22         return True
23     else:
24         return False
25 
26 if __name__=="__main__":
27     a_token,a_timestamp=custom()
28     result=service_check(a_token,a_timestamp)
29     if result:
30         print("用户校验成功,允许登录")
31     else:
32         print("用户校验失败,禁止登录")

1.3.base64模块介绍

base64是通用的加密方式,并且可以进行解密


1.4.base64模块的常用方法

Python基础入门(10)- 常用函数与高阶函数

 1 # coding:utf-8
 2 
 3 import base64
 4 
 5 def encode(data):
 6     if isinstance(data,str):
 7         data=data.encode('utf-8')
 8     elif isinstance(data,bytes):
 9         data=data
10     else:
11         raise TypeError("data need bytes or str")
12 
13     return base64.encodebytes(data).decode('utf-8')
14 
15 def decode(data):
16     if not isinstance(data,bytes):
17         raise TypeError("data need bytes or str")
18     return base64.decodebytes(data).decode('utf-8')
19 
20 if __name__=="__main__":
21     result=encode("你好,张三")
22     print(result)
23     new_result=decode(result.encode('utf-8'))
24     print(new_result)
 1 # coding:utf-8
 2 
 3 import base64
 4 
 5 #防止被别人破解,可以自己加一些加密手法
 6 replace_one='%'
 7 replace_two='$'
 8 def encode(data):
 9     if isinstance(data,str):
10         data=data.encode('utf-8')
11     elif isinstance(data,bytes):
12         data=data
13     else:
14         raise TypeError("data need bytes or str")
15 
16     _data=base64.encodebytes(data).decode('utf-8')
17     _data=_data.replace('5',replace_one).replace('2',replace_two)
18     return _data
19 
20 def decode(data):
21     if not isinstance(data,bytes):
22         raise TypeError("data need bytes or str")
23     _data=data.replace(replace_one.encode('utf-8'),b'5').replace(replace_two.encode('utf-8'),b'2')
24     return base64.decodebytes(_data).decode('utf-8')
25 
26 if __name__=="__main__":
27     result=encode("你好,张三")
28     print(result)
29     new_result=decode(result.encode('utf-8'))
30     print(new_result)

 

2.日志模块

2.1.日志的作用

程序的日记,记录程序的行为,记录程序重要信息记录


2.2.日志的等级

DEBUG < INFO < WARNING < ERROR < CRITICAL

Python基础入门(10)- 常用函数与高阶函数


2.3.logging模块的使用

Python基础入门(10)- 常用函数与高阶函数

Python基础入门(10)- 常用函数与高阶函数

 1 # encoding:utf-8
 2 
 3 import logging
 4 import os
 5 def init_log(path):
 6     if os.path.exists(path):
 7         mode='a'
 8     else:
 9         mode='w'
10 
11     logging.basicConfig(
12         level=logging.WARNING,
13         format='%(asctime)s %(filename)s [lines:%(lineno)d] %(levelname)s %(message)s',
14         filename=path,
15         filemode=mode
16     )
17     return logging
18 
19 if __name__=="__main__":
20     current_path=os.getcwd()
21     log_path=os.path.join(current_path,'back.log')
22     log=init_log(log_path)
23     log.info('你好,张三')
24     log.warning('你好,张三')
25     log.error('你好,张三')
26     log.debug('你好,张三')
27     logging.critical('你好,张三')
28 
29     print(logging.DEBUG)        #10
30     print(logging.INFO)         #20
31     print(logging.WARNING)      #30
32     print(logging.ERROR)        #40
33     print(logging.CRITICAL)     #50

 

3.虚拟环境

3.1.认识虚拟环境

Python基础入门(10)- 常用函数与高阶函数


3.2.Python中的虚拟环境工具

virtualenv:

  • 命令行下使用
  • ①安装:pip install virtualenv
  • ②选择安装目录
  • ③安装虚拟环境:virtualenv -p python3(安装环境的版本) penv(虚拟环境名称)
  • ④启动虚拟环境,进入./penv/bin目录输入active
  • ⑤退出虚拟环境:deactive

Python基础入门(10)- 常用函数与高阶函数

Python基础入门(10)- 常用函数与高阶函数

Python基础入门(10)- 常用函数与高阶函数

成功进入虚拟环境

Python基础入门(10)- 常用函数与高阶函数

Python基础入门(10)- 常用函数与高阶函数

 有的人在这可能报错,报错解决如下:

Python基础入门(10)- 常用函数与高阶函数

在PowerShell中输入"set-ExecutionPolicy RemoteSigned"来修改,在冒号后输入Y按回车

Python基础入门(10)- 常用函数与高阶函数

 

4.常用函数的集合

Python基础入门(10)- 常用函数与高阶函数

 1 # coding:utf-8
 2 
 3 #abs用法
 4 print(abs(-10),abs(0))  #10 0
 5 
 6 #all用法
 7 print(all(['a' in 'abc',True,None]))    #False
 8 
 9 #help用法
10 print(help(list))       #Help on class list in module builtins:....................
11 
12 #enumerate
13 for index,item in enumerate([444,555,666]):
14     print(index,item)
15 '''
16 0 444
17 1 555
18 2 666
19 '''
20 
21 #input用法
22 data=input("请输入信息:")
23 print(data)

Python基础入门(10)- 常用函数与高阶函数

 1 # coding:utf-8
 2 
 3 #isintance用法
 4 print(isinstance("aaa",str))        #True
 5 print(isinstance(123,str))          #False
 6 
 7 #type用法
 8 print(type((1,2,3)))                #<class 'tuple'>
 9 
10 #dir用法
11 print(dir(dict))                    # 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'..................
12 
13 #vars用法
14 class Test(object):
15     a=111
16     def __init__(self):
17         self.b=222
18         self.c=333
19 test=Test()
20 print(vars(test))               #{'b': 222, 'c': 333}
21 
22 #hasattr用法
23 print(hasattr(test,'a'))        #True
24 print(hasattr(test,'b'))        #True
25 print(hasattr(test,'c'))        #True
26 print(hasattr(test,'d'))        #False
27 print(hasattr(list,"append"))   #True

Python基础入门(10)- 常用函数与高阶函数

 1 # coding:utf-8
 2 
 3 class Test(object):
 4     a=111
 5     def __init__(self):
 6         self.b=222
 7         self.c=333
 8 test=Test()
 9 
10 #setattr用法
11 setattr(test,'d',444)
12 print(test.d)           #444
13 print(vars(test))       #{'b': 222, 'c': 333, 'd': 444}
14 
15 #getattr的用法
16 print(getattr(test,'d'))        #444
17 print(getattr(list,'append'))   #<method 'append' of 'list' objects>
18 
19 #any的用法
20 #any--->or
21 #all--->and
22 print(any([None,'',0,True]))    #True
23 print(any([None,'',0]))         #False

 

5.random模块

Python随机模块-random:

  • random.random
  • random.uniform
  • random.randint
  • random.choice
  • random.sample
  • random.randrange

Python基础入门(10)- 常用函数与高阶函数

Python基础入门(10)- 常用函数与高阶函数

Python基础入门(10)- 常用函数与高阶函数

choice可以传入列表、字符串等

Python基础入门(10)- 常用函数与高阶函数

sample返回指定个数元素,sample函数返回的都是列表

Python基础入门(10)- 常用函数与高阶函数

 

 randrange根据步长去取随机数,可以用作取奇偶数,相当于一个choice函数里面嵌套了一个range函数Python基础入门(10)- 常用函数与高阶函数

 1 # coding:utf-8
 2 
 3 import random
 4 
 5 gifts=['iphone','ipad','car','tv']
 6 
 7 def chioce_gifts():
 8     gift=random.choice(gifts)
 9     print('你得到了%s' % gift)
10 
11 def chioce_gift_new():
12     count=random.randrange(0,100,1)
13     if 0 <= count <= 50:
14         print('你中了一个iphone')
15     elif 50 < count <= 70:
16         print('你中了一个ipad')
17     elif 70 < count < 90:
18         print('你中了一个tv')
19     elif count >= 90:
20         print('你中了一个car')
21 
22 if __name__=="__main__":
23     chioce_gifts()
24     chioce_gift_new()
 1 # coding:utf-8
 2 
 3 import random
 4 
 5 happy = {
 6     "1": {"name": "富强福", "num": 0},
 7     "2": {"name": "和谐福", "num": 0},
 8     "3": {"name": "友善福", "num": 0},
 9     "4": {"name": "爱国福", "num": 0},
10     "5": {"name": "敬业福", "num": 0}
11 }
12 
13 print("集五福,迎新春~\n")
14 while True:
15     start = input("按下<Enter>键集五福,迎新春")
16     if isinstance(start, str):
17         number = random.randint(1, 5)
18         for k, v in happy.items():
19             if str(number) == k:
20                 v["num"] = v["num"] + 1
21                 print("获取到: {}".format(v["name"]))
22 
23         print("当前拥有的福:")
24         for k, v in happy.items():
25             print(v["name"], ":", v["num"], end="\t\t")
26         print("\n")

Python基础入门(10)- 常用函数与高阶函数

 

6.Python的高阶函数

6.1.迭代器

什么是迭代器:

  • 迭代是Python最强大的功能之一,是访问集合元素的一种方式。
  • 迭代器是一个可以记住遍历的位置的对象。
  • 迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。
  • 迭代器有两个基本的方法:iter() 和 next()
  • 字符串,列表或元组对象都可用于创建迭代器

如何生成迭代器:

Python基础入门(10)- 常用函数与高阶函数

迭代器的用法:

Python基础入门(10)- 常用函数与高阶函数

Python基础入门(10)- 常用函数与高阶函数

 1 #!/usr/bin/python3
 2  
 3 import sys         # 引入 sys 模块
 4  
 5 list=[1,2,3,4]
 6 it = iter(list)    # 创建迭代器对象
 7  
 8 while True:
 9     try:
10         print (next(it))
11     except StopIteration:
12         sys.exit()

迭代器对象可以使用常规for语句进行遍历:

1 #!/usr/bin/python3
2  
3 list=[1,2,3,4]
4 it = iter(list)    # 创建迭代器对象
5 for x in it:
6     print (x, end=" ")

迭代器常用方法之生成迭代器:

  • 在 Python 中,使用了 yield 的函数被称为生成器(generator)。
  • 跟普通函数不同的是,生成器是一个返回迭代器的函数,只能用于迭代操作,更简单点理解生成器就是一个迭代器。
  • 在调用生成器运行的过程中,每次遇到 yield 时函数会暂停并保存当前所有的运行信息,返回 yield 的值, 并在下一次执行 next() 方法时从当前位置继续运行。
  • 调用一个生成器函数,返回的是一个迭代器对象。

Python基础入门(10)- 常用函数与高阶函数

 1 #!/usr/bin/python3
 2  
 3 import sys
 4  
 5 def fibonacci(n): # 生成器函数 - 斐波那契
 6     a, b, counter = 0, 1, 0
 7     while True:
 8         if (counter > n): 
 9             return
10         yield a
11         a, b = b, a + b
12         counter += 1
13 f = fibonacci(10) # f 是一个迭代器,由生成器返回生成
14  
15 while True:
16     try:
17         print (next(f), end=" ")
18     except StopIteration:
19         sys.exit()
  • 打个比方的话,yield有点像断点。     加了yield的函数,每次执行到有yield的时候,会返回yield后面的值 并且函数会暂停,直到下次调用或迭代终止;
  • yield后面可以加多个数值(可以是任意类型),但返回的值是元组类型的。
 1 def get():
 2     m = 0
 3     n = 2
 4     l = ['s',1,3]
 5     k = {1:1,2:2}
 6     p = ('2','s','t')
 7     while True:
 8         m += 1
 9         yield m
10         yield m ,n ,l ,k ,p
11         
12 it = get()
13 print(next(it)) #1
14 print(next(it)) #(1, 2, ['s', 1, 3], {1: 1, 2: 2}, ('2', 's', 't'))
15 
16 print(next(it)) #2
17 print(type(next(it))) #<class 'tuple'>

迭代器常用方法之for循环获取:

Python基础入门(10)- 常用函数与高阶函数

迭代器小结:

 1 # coding:utf-8
 2 import sys
 3 
 4 #1.迭代器好处:
 5 #   当数据量过大时,比如人口普查这类信息,全部加载到内存里面再去读,就会很慢,通过迭代器,用迭代器对象按需逐个调去加载,而不是全部加载,性能会有很大的提高。
 6 
 7 #2.迭代器对象的创建
 8 #2.1使用iter()函数创建
 9 
10 person=["张三","李四","王五"]
11 person_iter=iter(person)
12 #2.2使用for循环创建
13 person_for=(i for i in person)
14 #2.3使用yield跟循环配合创建
15 def test():
16     for i in person:
17         yield i
18 person_yield=test()
19 
20 #3.读取迭代器对象信息
21 #3.1使用next()方法,调用,使用一次返回一次,不会全部返回
22 print(next(person_iter))    #张三
23 print(next(person_for))     #张三
24 print(next(person_yield))   #张三
25 #3.2使用循环将迭代器对象内容全部遍历出来
26 for i in person_iter:
27     print(i,end=" ")        #由于person_iter对象上面已经调用过一次了,所以打印李四 王五,下面同理 
28 print()
29 while True:
30     try:
31         print(next(person_for),end="")
32         print(next(person_yield),end="")
33         #输出:李四李四王五王五
34     except StopIteration:
35         sys.exit()

6.2.Python的高阶函数

6.2.1.filter

描述:

filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。

该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判断,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

语法:

以下是 filter() 方法的语法:

filter(function, iterable)

参数:

  • function -- 判断函数。
  • iterable -- 可迭代对象。

返回值:

返回一个迭代器对象

实例:

以下展示了使用 filter 函数的实例:

#!/usr/bin/python3
 
def is_odd(n):
    return n % 2 == 1
 
tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
newlist = list(tmplist)
print(newlist)    #[1, 3, 5, 7, 9]

6.2.2.map

描述:

map() 函数会根据提供的函数对指定序列做映射。

第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。

语法:

以下是 map() 方法的语法:

map(function, iterable, ...)

参数:

  • function -- 函数
  • iterable -- 一个或多个序列

返回值:

返回一个迭代器。

实例:

以下实例展示了 map() 的使用方法:

def square(x) :         # 计算平方数
    return x ** 2

map(square, [1,2,3,4,5])    # 计算列表各个元素的平方
list(map(square, [1,2,3,4,5]))   # 使用 list() 转换为列表
#[1, 4, 9, 16, 25]
list(map(lambda x: x ** 2, [1, 2, 3, 4, 5]))   # 使用 lambda 匿名函数
#[1, 4, 9, 16, 25]

6.2.3.reduce

描述:

reduce() 函数会对参数序列中元素进行累积。

函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。

注意:Python3.x reduce() 已经被移到 functools 模块里,如果我们要使用,需要引入 functools 模块来调用 reduce() 函数:

from functools import reduce

语法:

reduce() 函数语法:

reduce(function, iterable[, initializer])

参数:

  • function -- 函数,有两个参数
  • iterable -- 可迭代对象
  • initializer -- 可选,初始参数

返回值:

返回函数计算结果。

实例:

以下实例展示了 reduce() 的使用方法:

1 #!/usr/bin/python
2 from functools import reduce
3 
4 def add(x, y) :            # 两数相加
5     return x + y
6 sum1 = reduce(add, [1,2,3,4,5])   # 计算列表和:1+2+3+4+5
7 sum2 = reduce(lambda x, y: x+y, [1,2,3,4,5])  # 使用 lambda 匿名函数
8 print(sum1)    #15
9 print(sum2)    #15

 

 

上一篇:JAVA IO篇(持续更新中)


下一篇:Two Cakes