Python学习_08 函数、列表生成式和列表生成器


Python学习_08 函数、列表生成式和列表生成器
2018-04-14
1、上节课回顾
练习,先申明一个函数,第一个参数是整行,第二个参数是list类型,有一个默认值,默认值为[]列表
代码如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018\4\14 0014 23:01
# @Author  : xiexiaolong
# @File    : demon3.py
def f(x,l=[]):
    for i in range(x):
        l.append(i*i)
    print(l)
f(2)    #只传一个参数,默认传入第一个参数
f(4,[1,2])  #传入2个参数
f(x=3, l=[])    #最标准写法
结果如下:
D:\python\venv\Scripts\python.exe D:/python/第七节课函数类/demon3.py
[0, 1]
[1, 2, 0, 1, 4, 9]
[0, 1, 4]

Process finished with exit code 0

函数的关键字:
def     定义函数
return     返回值
pass     滤过,一般什么都不做,直接跳到下一个
exit(1)    直接退出
函数的参数;
*args      tuple参数,对应赋值
**kwargs      dict参数,对应赋值

pass表达式举例代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018\4\14 0014 23:51
# @Author  : xiexiaolong
# @File    : test.py

for letter in "Python":
    if letter == "h":
        pass
        print("pass test")
    print(letter)
结果:
D:\python\venv\Scripts\python.exe D:/python/第七节课函数类/test.py
P
y
t
pass test
h
o
n

Process finished with exit code 0
分析:如果letter等于h的时候pass,可以看到结果直接不输出h,直接到下一个

exit(1):    直接退出,举例;
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018\4\14 0014 23:51
# @Author  : xiexiaolong
# @File    : test.py
def hello():
    exit(1)
    print("hello")
hello()
结果:
D:\python\venv\Scripts\python.exe D:/python/第七节课函数类/test.py

Process finished with exit code 0
分析:可以看到输出结果为空,因为print之前有个exit,已经退出了函数,所以调用的时候输出为空

*args 和kwargs复习:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018\4\14 0014 23:51
# @Author  : xiexiaolong
# @File    : test.py
def test(m, *args, **kwargs):
    print("m = {0}".format(m))
    print("args = {0}".format(args))
    print("kwargs = {0}".format(kwargs))
test(10, 1, 11, 12, a=1, b=4, c=8)
结果;
D:\python\venv\Scripts\python.exe D:/python/第七节课函数类/test.py
m = 10
args = (1, 11, 12)
kwargs = {'a': 1, 'b': 4, 'c': 8}

Process finished with exit code 0

print,return,result
举例:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018\4\14 0014 23:51
# @Author  : xiexiaolong
# @File    : test.py
def add1(x, y):
    print(x+y)

def add2(x, y):
    return x+y

add1(5, 7)
result = add2(5, 7)
print(result)
结果:
D:\python\venv\Scripts\python.exe D:/python/第七节课函数类/test.py
12
12

Process finished with exit code 0
分析:pint直接打印出来,return返回值,用于其他方法中计算,例子中add1函数带参数调用直接输出结果,add2中需要定义一个变量再print才可以输出

2、匿名函数lambda
定义:匿名函数指一类无须定义标识符的函数或子程序。Python用lambda语法定义匿名函数,只需用表达式而无需申明
add = lambda x,y:x+y
等同于:
def add(x, y):
    return x+y
举例:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018\4\14 0014 23:51
# @Author  : xiexiaolong
# @File    : test.py
add = lambda x,y:x + y
print(add(4,5))
结果;
D:\python\venv\Scripts\python.exe D:/python/第七节课函数类/test.py
9

Process finished with exit code 0
分析:print的时候传入2个参数4和5,输出结果是x+y 就是4+5 = 9

3、高阶函数
高阶函数:就是把函数当成参数传递的一种函数
一、高阶函数map:会根据提供的函数对指定序列做映射
语法:
map(function, iterable, ...)
返回结果,python2.x返回列表,python3.x返回迭代器
例子:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018\4\14 0014 23:51
# @Author  : xiexiaolong
# @File    : test.py

def f(x):
    return x*x
for i in map(f,[1, 2, 3, 4]):
    print(i)
返回结果:
D:\python\venv\Scripts\python.exe D:/python/第七节课函数类/test.py
1
4
9
16

Process finished with exit code 0
二、高阶函数filter
         函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。
         该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。
例子:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018\4\14 0014 23:51
# @Author  : xiexiaolong
# @File    : test.py

def number1(n):
    return n % 2 == 1
number2 = filter(number1,[1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(list(number2))
结果:
D:\python\venv\Scripts\python.exe D:/python/第七节课函数类/test.py
[1, 3, 5, 7, 9]

Process finished with exit code 0
分析:先定义一个函数,如果参数除以2余数等于1,则返回True,否则返回False
    然后函数返回的结果作为filter的判断条件参数,如果除以2余数等于1,filter的参数就是True,则留下,否则过滤,最终结果就是过滤调不符合条件的
三、高阶函数reduce:
        函数会对参数序列中元素进行累积,函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给reduce中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。
 例子:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018\4\14 0014 23:51
# @Author  : xiexiaolong
# @File    : test.py
from functools import reduce
def add (x, y):
    return x + y
reduce(add,[1, 2, 3, 4, 5, 6])
print(reduce(add,[1, 2, 3, 4, 5, 6]))
结果:
D:\python\venv\Scripts\python.exe D:/python/第七节课函数类/test.py
21

Process finished with exit code 0
 分析:先定义一个函数add,2个参数相加,然后用reduce函数,传入第一个参数add函数的结果,然后一个可迭代的对象,执行过程是1和2相加的结果和3再相加,结果再和4相加最终得到21
四、高阶函数sorted,比较常用的函数
         函数对所有可迭代的对象进行排序操作。(sort 与 sorted 区别:sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。list 的 sort 方法返回的是对已经存在的列表进行操作,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。)
语法:
sorted (iterable, key, reverse)
iterable  一个可迭代的对象
key排序的对象
reverse  bool值,如果为True反序,默认为False
例子1dict排序:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018\4\14 0014 23:51
# @Author : xiexiaolong
# @File : test.py

print ( sorted ([ 1 , 34 , 324 , 23 , 45 , 2 , 345 , 689 ]))
结果:
D:\python\venv\Scripts\python.exe D:/python/第七节课函数类/test.py
[1, 2, 23, 34, 45, 324, 345, 689]

Process finished with exit code 0
分析:key省略,reverse默认是False
例子2:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018\4\14 0014 23:51
# @Author  : xiexiaolong
# @File    : test.py
m = dict(a=1, c=20, d=10, b=15)
print(m)
print("如下排序默认只排序key值:")
print(sorted(m))
print("如下排序中,把m.items这个元素的(key和value)当作参数x,x[0]代表第一个值:")
print(sorted(m.items(),key = lambda x : x[0]))
print("如下排序中,把m.items这个元素的(key和value)当作参数x,x[1]代表第二个值:")
print(sorted(m.items(),key = lambda x : x[1]))
print("然后转换成dict:")
print(dict(sorted(m.items(),key = lambda x : x[1])))
结果:
D:\python\venv\Scripts\python.exe D:/python/第七节课函数类/test.py
{'a': 1, 'c': 20, 'd': 10, 'b': 15}
如下排序默认只排序key值:
['a', 'b', 'c', 'd']
如下排序中,把m.items这个元素的(key和value)当作参数x,x[0]代表第一个值:
[('a', 1), ('b', 15), ('c', 20), ('d', 10)]
如下排序中,把m.items这个元素的(key和value)当作参数x,x[1]代表第二个值:
[('a', 1), ('d', 10), ('b', 15), ('c', 20)]
然后转换成dict:
{'a': 1, 'd': 10, 'b': 15, 'c': 20}

Process finished with exit code 0
4、列表生成式和生成器
一、列表生成式
         列表生成式,是Python内置的一种极其强大的生成list的表达式。
如果要生成一个list[1, 2, 3, 4, 5, 6, 7, 8, 9]可以用rang(1, 10);
如果要生成[1*1 , 2*2 , 3*3 , ... , 10*10] 可以使用循环:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018\4\16 0016 0:31
# @Author  : xiexiaolong
# @File    : test2.py
m = []
for i in range(1, 10):
    m.append(i*i)
print(m)
结果:
D:\python\venv\Scripts\python.exe D:/python/第七节课函数类/test2.py
[1, 4, 9, 16, 25, 36, 49, 64, 81]

Process finished with exit code 0
列表生成式可以用一句代替以上的繁琐循环来完成上面的操作::
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018\4\16 0016 0:31
# @Author : xiexiaolong
# @File : test2.py
L = list (i*i for i in range ( 1 , 10 ))
print (L)
列表生成式可以加if条件、for循环里边再加for循环,做一个九宫格例子:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018\4\16 0016 0:31
# @Author  : xiexiaolong
# @File    : test2.py
def jgg():
    count = 1
    for A in[x for x in range(1, 10)]:
        for B in[x for x in range(1, 10) if x != A]:
            for C in[x for x in range(1, 10) if x != A and x != B]:
                for D in[x for x in range(1, 10) if x != A and x != B and x != C]:
                    for E in[x for x in range(1, 10) if x != A and x != B and x != C and x != D]:
                        for F in[x for x in range(1, 10) if x != A and x != B and x != C and x != D and x != E]:
                            for G in[x for x in range(1, 10) if x != A and x != B and x != C and x != D and x != E and x != F]:
                                for H in[x for x in range(1, 10) if x != A and x != B and x != C and x != D and x != E and x != F and x != G]:
                                    for I in[x for x in range(1, 10) if x != A and x != B and x != C and x != D and x != E and x != F and x != G and x != H]:
                                        if A + B + C == D + E + F == G + H + I == A + D + G == B + E + H == C + F + I == A + E + I == C + E + G == 15:
                                            print('''
                                        第{9}种方法:
                                        ---------------
                                        | {0} | {1} | {2} |
                                        | {3} | {4} | {5} |
                                        | {6} | {7} | {8} |
                                        ---------------
                                        '''.format(A,B,C,D,E,F,G,H,I,count))
                                            count += 1
jgg()
结果:
D:\python\venv\Scripts\python.exe D:/python/第七节课函数类/test2.py

                                        第1种方法:
                                        ---------------
                                        | 2 | 7 | 6 |
                                        | 9 | 5 | 1 |
                                        | 4 | 3 | 8 |
                                        ---------------
                                        

                                        第2种方法:
                                        ---------------
                                        | 2 | 9 | 4 |
                                        | 7 | 5 | 3 |
                                        | 6 | 1 | 8 |
                                        ---------------
                                        

                                        第3种方法:
                                        ---------------
                                        | 4 | 3 | 8 |
                                        | 9 | 5 | 1 |
                                        | 2 | 7 | 6 |
                                        ---------------
                                        

                                        第4种方法:
                                        ---------------
                                        | 4 | 9 | 2 |
                                        | 3 | 5 | 7 |
                                        | 8 | 1 | 6 |
                                        ---------------
                                        

                                        第5种方法:
                                        ---------------
                                        | 6 | 1 | 8 |
                                        | 7 | 5 | 3 |
                                        | 2 | 9 | 4 |
                                        ---------------
                                        

                                        第6种方法:
                                        ---------------
                                        | 6 | 7 | 2 |
                                        | 1 | 5 | 9 |
                                        | 8 | 3 | 4 |
                                        ---------------
                                        

                                        第7种方法:
                                        ---------------
                                        | 8 | 1 | 6 |
                                        | 3 | 5 | 7 |
                                        | 4 | 9 | 2 |
                                        ---------------
                                        

                                        第8种方法:
                                        ---------------
                                        | 8 | 3 | 4 |
                                        | 1 | 5 | 9 |
                                        | 6 | 7 | 2 |
                                        ---------------
                                        

Process finished with exit code 0
二、列表生成器:
         通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的。而且,创建一个包含100万个元素的列表,不仅占用很大的存储空间,如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。
所以,如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢?这样就不必创建完整的list,从而节省大量的空间。在Python中,这种一边循环一边计算的机制,称为生成器(Generator)。
要创建一个generator,有很多种方法。第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018\4\16 0016 0:31
# @Author : xiexiaolong
# @File : test2.py
L = [x * x for x in range ( 1 , 10 )]
print (L)
G = (x * x for x in range ( 1 , 10 ))
print (G)
结果;
D:\python\venv\Scripts\python.exe D:/python/第七节课函数类/test2.py
[1, 4, 9, 16, 25, 36, 49, 64, 81]
<generator object <genexpr> at 0x000000000261CF10>

Process finished with exit code 0
分析:例子中L是一个list而G 是一个generator要打印出G的元素,可以通过next函数:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018\4\16 0016 0:31
# @Author : xiexiaolong
# @File : test2.py
L = [x * x for x in range ( 1 , 10 )]
print (L)
G = (x * x for x in range ( 1 , 10 ))
print ( next (G))
print ( next (G))
print ( next (G))
结果:
D:\python\venv\Scripts\python.exe D:/python/第七节课函数类/test2.py
[1, 4, 9, 16, 25, 36, 49, 64, 81]
1
4
9

Process finished with exit code 0
分析:next调一次之后,调用过的将不会再次遍历到,所以没掉用一次,输出下一个遍历的结果
generator也可以用for循环打印出所有的:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018\4\16 0016 0:31
# @Author  : xiexiaolong
# @File    : test2.py
L = [x * x for x in range(1, 10)]
print(L)
G = (x * x for x in range(1, 10))
for i in G:
    print(list(G))
结果:
D:\python\venv\Scripts\python.exe D:/python/第七节课函数类/3233.py
[1, 4, 9, 16, 25, 36, 49, 64, 81]
[4, 9, 16, 25, 36, 49, 64, 81]

Process finished with exit code 0
5、yield
yield 是一个类似 return 的关键字,只是这个函数返回的是个生成器:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018\4\16 0016 0:31
# @Author  : xiexiaolong
# @File    : test2.py

def test():
    for i in range(1, 10):
        yield i
        print(i)
x = test()
print(x)
for y in x:
    print(y)
结果:
D:\python\venv\Scripts\python.exe D:/python/第七节课函数类/test2.py
<generator object test at 0x00000000025ECF10>
1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9

Process finished with exit code 0




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值