day7-20180414笔记

笔记:Python的函数类,列表生成式和生成器

 

一、Python的函数类

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/14 20:09
# @Author  : lingxiangxiang
# @File    : demon1.py

# 申明一个函数,第一个参数是整型, 第二个参数是list类型,
# l 有一个默认值,默认值为[]空列表

def f(x,l=[]):
    for i in range(x):
        l.append(i*i)
    print(l)

# f(2) = f(2, l=[])



f(2)
# 输出什么[0, 1]

f(3,[3,2,1])
# 结果: [3, 2, 1, 0, 1, 4]

f(x=3, l=[])
# 结果: [0, 1, 4]

 

函数的关键字
def 定义函数
return 返回这
pass 滤过
exit(1) 直接退出
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/14 20:22
# @Author  : yangyuanqiang
# @File    : demon2.py

def add1(x, y):
    print(x+y)

add1(1, 2)  #传参,1,2的参数

以上实例输出的结果

3    #直接输出

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/14 20:22
# @Author  : yangyuanqiang
# @File    : demon2.py

def add2(x, y):
    return x + y  #返回值


result = add2(1, 2)  #调用函数传参,赋值给result变量,再执行print打印
print(result)

以上实例输出的结果

3

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/14 20:22
# @Author  : yangyuanqiang
# @File    : demon2.py

def hello():
    pass  #过滤
    print("hello")

hello()

以上实例输出的结果

hello

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/14 20:22
# @Author  : yangyuanqiang
# @File    : demon2.py


def helloworld():
    exit(1)      #直接退出
    print("hello world")


helloworld()

以上实例输出的结果

    #exit(1)直接退出,所以不会执行下面的结果

 

函数的参数
*args tuple参数,对应赋值
**kwargs dict参数,对应赋值
fun(*args, **keargs)
fun(1, 2, 3, 4, 5, a=10, b=40)

args = (1, 2, 3, 4, 5)
keargs = (a=10, b=40)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/14 20:22
# @Author  : yangyuanqiang
# @File    : demon2.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=10,b=20)

以上实例输出的结果

m = 10
args = (1, 11, 12)
kwargs = {'b': 20, 'a': 10}

 

匿名函数
def add(x, y):
return x + y

add = lambda x,y:x + y

高阶函数    装逼函数
都是可以通过代码逻辑实现的。
都是可以通过代码逻辑实现的
但是你写的函数的负责程序,或者算法不一定有人家内置的好

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/14 20:38
# @Author  : yangyuanqiang
# @File    : demon3.py





def f(x):
    return x*x

print(map(f, [1, 2, 3, 4]))
print(list((map(f, [1, 2, 3, 4]))))    #强制转换成列表
for i in map(f, [1, 2, 3, 4]):
    print(i)

以上实例输出的结果

<map object at 0x101978748>
[1, 4, 9, 16]
1
4
9
16

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/14 20:38
# @Author  : yangyuanqiang
# @File    : demon33.py




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

print(reduce(add, [1, 2, 3, 4, 5, 6]))
# 1, 2   = 3
# 3, 3   = 6
# 6, 4   = 10
# 10, 5 = 15
# 15, 6 = 21
输出的结果为:21

 

唯一用的比较多的,就是sorted
sorted(iterable, key, reverse)
iterable 一个可迭代的对象
key 对什么进行排序
reverse bool类型,如果为true为反序, 默认为false
返回值是一个list
print(sorted([1, 4, 342, 3, 45, 76, 435, 34], reverse=True))

结果为:
[435, 342, 76, 45, 34, 4, 3, 1]

 

m = dict(a=1, c=10, b=20, d=15)
print(m)
print(sorted(m.items()))
print(sorted(m.items(), key=lambda x: x[0]))
print(dict(sorted(m.items(), key=lambda x: x[1])))
print(sorted(m.items(), key = lambda d:d[1], reverse = True))

以上实例输出的结果

{'b': 20, 'c': 10, 'a': 1, 'd': 15}
[('a', 1), ('b', 20), ('c', 10), ('d', 15)]
[('a', 1), ('b', 20), ('c', 10), ('d', 15)]
{'b': 20, 'a': 1, 'c': 10, 'd': 15}
[('b', 20), ('d', 15), ('c', 10), ('a', 1)]

 

字典有三种初始化的方法

d1 = dict(a=1, b=2)
d2 = {"a": 1, "b": 2}
d3 = dict([("a", 1), ("b", 2)])
print(d1, d2, d3)

以上实例输出的结果

{'b': 2, 'a': 1} {'b': 2, 'a': 1} {'b': 2, 'a': 1}

 



二、列表生成式和生成器

1、列表生成式

列表生成式
[exp for val in collection if condition]

以九宫格为例:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/14 21:34
# @Author  : yangyuanqiang
# @File    : demon4.py



'''

列表生成式


生成器

'''

# 列表生成式
def jgg():
    count = 1
    number = list()
    for i in range(1, 10):
        number.append(i)
    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 != H]:
                                        # print("A = {0} B = {1} C = {2} D = {3} E = {4} F = {5} G = {6} H = {7} I {8}".format(A, B, C, D, E, F, G, H, I))
                                        if (A + B + C == D + E + F == G + H + I == A + D + G == B + E + H == C + F + I == A + E + I == G + E + C == 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()

以上实例输出的结果

第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 |
                                                  -------------

 

2、生成器

生成器
方法一:
(exp for val in collection if condition)
方法二:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/14 21:34
# @Author  : yangyuanqiang
# @File    : demon4.py

a1 = (x for x in range(1, 10) if x%2==0)
print(a1)
# python2   a1.next()
print(next(a1)) #python3 是直接调用next方法
print("##"*5)   #输出10个*
for i in a1:
    print(i)

以上实例输出的结果

<generator object <genexpr> at 0x102081b48>
2
##########
4
6
8

 

a2 = [x for x in range(1, 10) if x%2==0]     #列表形式
print(a2)

以上实例输出的结果

[2, 4, 6, 8]

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/14 21:34
# @Author  : yangyuanqiang
# @File    : demon4.py


def test():
    a = 1
    for i in range(1, 10):
        yield i
        # return i
        a += 1
        # return i
#return和yield的区别
# yield 可以理解成return,但是比return多一些角色
# yiele 每次都返回,但是下一次取值时,从上一次yield的下一行开始
m = test()
print(m)

以上实例输出的结果

<generator object test at 0x102081b48>

 

 

练习题

对/etc/passwd文件排序操作,以uid用户ID号进行排序,输出的结果:
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin

passwd文件内容:

adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
avahi-autoipd:x:170:170:Avahi IPv4LL Stack:/var/lib/avahi-autoipd:/sbin/nologin
systemd-bus-proxy:x:999:997:systemd Bus Proxy:/:/sbin/nologin
systemd-network:x:998:996:systemd Network Management:/:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
polkitd:x:997:995:User for polkitd:/:/sbin/nologin
tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
ntp:x:38:38::/etc/ntp:/sbin/nologin
nscd:x:28:28:NSCD Daemon:/:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
nginx:x:1000:1000::/home/nginx:/sbin/nologin
zabbix:x:996:994:Zabbix Monitoring System:/var/lib/zabbix:/sbin/nologin

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/15 17:10
# @Author  : yangyuanqiang
# @File    : 用户列表排序.py

'''
对/etc/passwd文件排序操作,以uid用户ID号进行排序,输出的结果:
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin

'''



import codecs


def px(item):
    pass    #滤过
result = "" #空字符串
with codecs.open("passwd", "r") as f:   #读取文件,自动关闭文件
    result = sorted(f.readlines(), key=lambda item: int(item.split(":")[2]))    #f.readlines() 一行一行的读,key=lambda 匿名函数,int整数,split进行切片,以":"为分隔符,取第三列uid

with codecs.open("sortPasswd", "w") as f:   #写入到新的文件中
    f.writelines(result)    #一行一行的写入到文件中

以上实例输出的结果:在当前目录下生成 sortPasswd文件,内容如下:

root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nscd:x:28:28:NSCD Daemon:/:/sbin/nologin
ntp:x:38:38::/etc/ntp:/sbin/nologin
tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
avahi-autoipd:x:170:170:Avahi IPv4LL Stack:/var/lib/avahi-autoipd:/sbin/nologin
zabbix:x:996:994:Zabbix Monitoring System:/var/lib/zabbix:/sbin/nologinpolkitd:x:997:995:User for polkitd:/:/sbin/nologin
systemd-network:x:998:996:systemd Network Management:/:/sbin/nologin
systemd-bus-proxy:x:999:997:systemd Bus Proxy:/:/sbin/nologin
nginx:x:1000:1000::/home/nginx:/sbin/nologin

 

posted @ 2018-04-15 16:12  Ivan_yyq  阅读(104)  评论(0编辑  收藏  举报