跟着ALEX 学python day3集合 文件操作 函数和函数式编程

声明 :

 

文档内容学习于

http://www.cnblogs.com/xiaozhiqi/ 

 

一、 集合

集合是一个无序的,不重复的数据组合,主要作用如下

1.去重 把一个列表变成集合 ,就自动去重了

2.关系测试,测试2组数据的之前的交集,差集,并集等关系

 

 

去重,直接将列表变成集合

[root@master day3]# cat set.py 
#!/usr/bin/env python3
list = [1,2,5,8,5,6,7,7]
list = set(list)
print (list,type(list))


[root@master day3]# ./set.py 
{1, 2, 5, 6, 7, 8} <class 'set'>   #直接去重了

 

交集, intersection 。 就是将2个列表中,相同的取出来

下面list 和list2中    5和 8是重复,可以直接将他们取出。

[root@master day3]# cat set.py 
#!/usr/bin/env python3


list = [1,2,5,8,5,6,7,7]
list = set(list)
list2 = set([5,555,256,777,8])
print ( list.intersection(list2))


[root@master day3]# ./set.py 
{8, 5}

 

 

并集(合集), union  2个列表合并去重

 

[root@master day3]# cat set.py 
#!/usr/bin/env python3


list = [1,2,5,8,5,6,7,7]
list = set(list)
list2 = set([5,555,256,777,8])
print ( list.union(list2))


[root@master day3]# ./set.py 
{256, 1, 2, 5, 6, 7, 8, 777, 555}

 

 

差集,difference  就是2个列表,对比。打印独有部分

[root@master day3]# cat ./set.py 
#!/usr/bin/env python3
list = [1,2,5,8,5,6,7,7]
list = set(list)
list2 = set([5,555,256,777,8])
print ( list.difference(list2))    #将list和list2对比。打印只有list中独有的部分


[root@master day3]# ./set.py  
{1, 2, 6, 7}

 

 

对称差集

就是将2个列表中,相互没有的都取出来了。

[root@master day3]# cat ./set.py 
#!/usr/bin/env python3
list = [1,2,5,8,5,6,7,7]
list = set(list)
list2 = set([5,555,256,777,8])
print ( list.symmetric_difference(list2))



[root@master day3]# ./set.py 
{256, 1, 2, 6, 7, 777, 555}

 

 

 

 

 

 

 

 

子集,父集

是否存在包含的关系

[root@master day3]# cat ./set.py 
#!/usr/bin/env python3


list = [1,2,5,8,5,6,7,7]
list3 = set([1,7])

list = set(list)
list2 = set([5,555,256,777,8])


print ( list.issubset(list2))                       #子集,是否被包含
print ( list3.issubset(list))
print ( list.issuperset(list2))                     #父集,是否包含
print ( list.issuperset(list3))


[root@master day3]# ./set.py 
False
True
False
True

 

 

判断是否有交集  isdisjoint

如果2个列表没有交集, 就返回ture。

[root@master day3]# cat set.py 
#!/usr/bin/env python3


list = [1,2,5,8,5,6,7,7]
list = set(list)
list2 = set([5,555,256,777,8])
list3 = set([1,6])
print ( list3.isdisjoint(list))
print ( list3.isdisjoint(list2))

[root@master day3]# ./set.py 
False
True

 

 

 

也可以使用以下字符串进行操作

s | t   s和t的并集
s & t   s和t的交集
s - t   求差集
s ^ t   求对称差集
len(s)  集合中项数
max(s)  最大值
min(s)  最小值

 

添加 

add  添加一项

[root@master day3]# cat set.py 
#!/usr/bin/env python3

list = [1,2,5,8,5,6,7,7]
list = set(list)
list.add("ssdd")


print ( list )
[root@master day3]# ./set.py 
{1, 2, 5, 6, 7, 8, 'ssdd'}

 

update 添加多项

[root@master day3]# cat set.py 
#!/usr/bin/env python3


list = [1,2,5,8,5,6,7,7]
list = set(list)
list.update([555,666,888])
print ( list )


[root@master day3]# ./set.py 
{1, 2, 5, 6, 7, 8, 555, 888, 666}

 

 

删除

remove,因为集合本生就是去重的,所以,删除的话。就是都删除了 。

[root@master day3]# cat set.py 
#!/usr/bin/env python3


list = [1,2,5,8,5,6,7,7]
list = set(list)
list.remove(2)
print ( list )


[root@master day3]# ./set.py 
{1, 5, 6, 7, 8}

 

pop  随机删除 。

[root@master day3]# cat set.py 
#!/usr/bin/env python3

list = [1,2,5,8,5,6,7,7]
list = set(list)
list.pop()
print (list)


[root@master day3]# ./set.py 
{2, 5, 6, 7, 8}

 

 

discard

也是删除,和remove相似,但是remove指定一个不存在的值的时候会报错、discard不会报错

[root@master day3]# cat set.py 
#!/usr/bin/env python3


list = [1,2,5,8,5,6,7,7]
list = set(list)


list.discard(555)               #指定不存在的值,程序也不会报错。
list.discard(8)

print (list)




[root@master day3]# ./set.py 
{1, 2, 5, 6, 7}

 

 

文件操作

 

文件操作步骤

1. 打开文件

2.通过文件句柄进行操作

3.关闭文件

 

基本的文化操作

读取文件

linux中

当文件和脚本在同一个目录下时, 可以直接打开

 

[root@localhost python]# ls
dictionary.py  file_op.py  guess.py  name2.py  name.py  tuple.py  yesterday.txt
[root@localhost python]# cat file_op.py 
#!/usr/bin/env python3

data = open ("yesterday.txt").read()                   #直接打开文件  
print (data)
[root@localhost python]# 

 

windows中

因为windows  默认是 GBK的编码格式, 所以在windows中打开的话。需要定义编码字符集

# Author ricky

data = open("yesterday",encoding="utf-8" ).read()   #  定义字符集

print (data )

 

 

否则会报错

Traceback (most recent call last):
  File "E:/个人/python/day3/file_op.py", line 3, in <module>
    data = open("yesterday").read()
UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 124: illegal multibyte sequence

 

 

这是读取了文件,一般情况下,如果要修改。就是会将打开这个文件写成一个变量。

f = open("yesterday",encoding="utf-8")

data = f.read()

print (data )
f.close()     # 关闭文件

 

然后读取文件的话,其实就是加载文件到内存中。 然后你的程序的光标,其实就是第一次读的内存指针。所以当有第二个变量指过去的时候。其实还是现实是之前的内存指针。

[root@localhost python]# cat yesterday.txt 
aaaaaa
bbbbbb
ccccc
[root@localhost python]# cat ./file_op.py 
#!/usr/bin/env python3

f = open ("yesterday.txt")

data = f.read()
data2 = f.read()
print ( data )
print ( "data2==============", data2 )

[root@localhost python]# ./file_op.py aaaaaa bbbbbb ccccc data2==============

 

 

逐行读取  readline

read是读取全部文件, readline 是逐行读取

[root@master day3]# cat yesterday.txt 
seems the love I've known,
看起来我所知道的爱情
has always been the most destructive kind.
好像总是变成破坏性的那种
I guess that's why now I feel so old before my time.
我猜这就是为什么我感到如此苍老,比起我的真实年龄
Yesterday When I was young
往日当我还年轻时
The taste of life was sweet
生命的感受如此美好
As rain upon my tongue
就像雨滴滴落我的舌尖
I teased at life as if
[root@master day3]# cat file_op.py #!/usr/bin/env python3 f = open("yesterday.txt") print (f.readline())

[root@master day3]# ./file_op.py seems the love I've known,

 

读取前5行

可以用for循环+ readline实现

[root@master day3]# cat  file_op.py 
#!/usr/bin/env  python3


f = open("yesterday.txt")

for i in range(5):
    print (f.readline())

f.close()

[root@master day3]# ./file_op.py seems the love I've known, 看起来我所知道的爱情 has always been the most destructive kind. 好像总是变成破坏性的那种 I guess that's why now I feel so old before my time.

 

 打印全部文件 

 

可以直接用for进行循环

这种循环效率最好。他就是加载一行,打印一行,然后内存中再去除一行 。

[root@master day3]# cat file_op.py 
#!/usr/bin/env  python3


f = open("yesterday.txt")
for i in f:
  print  ( i.strip() )

f.close()

[root@master day3]# ./file_op.py seems the love I've known, 看起来我所知道的爱情 has always been the most destructive kind. 好像总是变成破坏性的那种 I guess that's why now I feel so old before my time. 我猜这就是为什么我感到如此苍老,比起我的真实年龄 Yesterday When I was young 往日当我还年轻时 The taste of life was sweet 生命的感受如此美好 As rain upon my tongue 就像雨滴滴落我的舌尖 I teased at life as if

 

指定打印到某一行。 将这行进行输出(---------)。

可以自己写个计数器,然后进行判断

[root@master day3]# cat file_op.py 
#!/usr/bin/env  python3

f = open("yesterday.txt")
count = 0
for i  in f :
    if count == 5:
        print ("=====================")
    print ( i.strip() )
    count += 1

f.close()

[root@master day3]# ./file_op.py seems the love I've known, 看起来我所知道的爱情 has always been the most destructive kind. 好像总是变成破坏性的那种 I guess that's why now I feel so old before my time. ===================== 我猜这就是为什么我感到如此苍老,比起我的真实年龄 Yesterday When I was young 往日当我还年轻时 The taste of life was sweet 生命的感受如此美好 As rain upon my tongue 就像雨滴滴落我的舌尖 I teased at life as if

 

打印5到 10行 

[root@master day3]# cat file_op.py 
#!/usr/bin/env  python3


f = open("yesterday.txt")
count = 0

for i  in f :
    if count >= 5 and  count <= 10 :
        print ( i.strip() )
    count += 1

f.close()

[root@master day3]# ./file_op.py 我猜这就是为什么我感到如此苍老,比起我的真实年龄 Yesterday When I was young 往日当我还年轻时 The taste of life was sweet 生命的感受如此美好 As rain upon my tongue

 

 

 

还有一种方法 

可以使用readlines

注意 是readlines   不是readline。

readlines 将文件内容,变成了列表。   所以他每次都会将整个文件进行转换。 如果是大文件。会影响性能。所以不推荐。

但是 , 因为列表有下标。 所以。在处理小文件的时候。 可能会写起来方便点。  但是不推荐。 

 

[root@master day3]# cat file_op.py 
#!/usr/bin/env  python3


f = open("yesterday.txt")


for i  in  f.readlines():
    print ( i.strip() )   # 可以使用 strip  去掉多于的空行和空格 

f.close()

[root@master day3]# ./file_op.py seems the love I've known, 看起来我所知道的爱情 has always been the most destructive kind. 好像总是变成破坏性的那种 I guess that's why now I feel so old before my time. 我猜这就是为什么我感到如此苍老,比起我的真实年龄 Yesterday When I was young 往日当我还年轻时 The taste of life was sweet 生命的感受如此美好 As rain upon my tongue 就像雨滴滴落我的舌尖 I teased at life as if

 

 

指定打印到某一行。 将这行进行输出(---------)。

其实 readlines 是将文件变成了 列表。 所以每个元素都是都下标。我们可以使用下标进行判断,来实现。

[root@master day3]# cat file_op.py 
#!/usr/bin/env  python3


f = open("yesterday.txt")


for index,line in enumerate(f.readlines()):
    if index == 5 :
        print ( "-------------------------" )
    print  (  line.strip() )

f.close()

[root@master day3]# ./file_op.py seems the love I've known, 看起来我所知道的爱情 has always been the most destructive kind. 好像总是变成破坏性的那种 I guess that's why now I feel so old before my time. ------------------------- 我猜这就是为什么我感到如此苍老,比起我的真实年龄 Yesterday When I was young 往日当我还年轻时 The taste of life was sweet 生命的感受如此美好 As rain upon my tongue 就像雨滴滴落我的舌尖 I teased at life as if

 

 

这样也可以实现,打印5-10的内容

注意下标是从 0 开始的。 所以要算好行数。

 

[root@master day3]# cat file_op.py 
#!/usr/bin/env  python3


f = open("yesterday.txt")


for index,line in enumerate(f.readlines()):
    if index  > 5 and  index < 10:
        print  (  index , line.strip() )
f.close()

[root@master day3]# ./file_op.py 6 Yesterday When I was young 7 往日当我还年轻时 8 The taste of life was sweet 9 生命的感受如此美好

 

 

 

 

 

 

 

写文件

在python中。 如果打开文件后,需要制定操作类型, 读了 就不能写。  写了就不能读。

 

r  读取文件

[root@localhost python]# cat  file_op.py 
#!/usr/bin/env python3

f = open ("yesterday.txt","r")

data = f.read()
data2 = f.read()

print ( data )
print ( "data2==============", data2 )
[root@localhost python]# ./file_op.py 
aaaaaa
bbbbbb
ccccc

data2============== 

 

w  写文件

这边需要注意,写文件的话,w参数每次写都是覆盖。 会将原本的文件内容删除。

[root@localhost python]# cat yesterday.txt 
aaa
bbb
ccc
[root@localhost python]# cat file_op.py #!/usr/bin/env python3 f = open ("yesterday.txt","w") f.write ("123456789")
[root@localhost python]# ./file_op.py [root@localhost python]# cat yesterday.txt 123456789[root@localhost python]#

 

同时 他也可以创建新的文件

[root@localhost python]# ls
dictionary.py  file_op.py  guess.py  name2.py  name.py  tuple.py  yesterday.txt
[root@localhost python]# cat file_op.py 
#!/usr/bin/env python3

f = open ("tomorrow.txt","w")
f.write ("123456789")
[root@localhost python]# ./file_op.py [root@localhost python]# ls dictionary.py file_op.py guess.py name2.py name.py tomorrow.txt tuple.py yesterday.txt

 

 

 

 a  append   追加写

 

[root@localhost python]# cat yesterday.txt 
123456789

[root@localhost python]# cat file_op.py 
#!/usr/bin/env python3

f = open ("yesterday.txt","a")


f.write ("ppp\n")
f.write ("ooo\n")
[root@localhost python]# ./file_op.py 
[root@localhost python]# cat yesterday.txt 
123456789

ppp
ooo

 

其他的一些使用方法

tell

就是告诉你现在的文件指针位置的。 注意:它不是按行来算的,是字符串的位置来算的。

[root@master day3]# cat file_op.py 
#!/usr/bin/env  python3


f = open("yesterday.txt")


print (f.tell())
print(f.readline().strip())
print (f.tell())
f.close()

[root@master day3]# ./file_op.py 0 seems the love I've known, 27

 

 

seek

指定文件指正到固定位置。实际情况中,因为使用中,因为你不能确定,具体的字符串的位置。所以一般都是指向0。

[root@master day3]# cat file_op.py 
#!/usr/bin/env  python3


f = open("yesterday.txt")

print (f.tell())
print(f.readline().strip())
print (f.tell())
f.seek(0)
print (f.tell())
print(f.readline().strip())
f.close()

[root@master day3]# ./file_op.py 
0
seems the love I've known,
27
0
seems the love I've known,

 

flush

一般我们写,读文件都是先存储到内存中的 ,当到了一定的量之后,它才会写到磁盘上面。  flush就是可以使 立刻将内存中的内容写到磁盘上面。

这个在window上进行测试

现在有个空文件
111.txt
然后插入一条语句
E:\>python
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (
AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open("111.txt",'w')
>>> f.write("hello")

 再次打开,发现文件还是空的。

 

 

 这个时候输入

 

>>> f.flush()

 

再次打开文件, 发现文件有内容了。

 

可以用来打印进度条 ,可以试试下面的代码。

# Author ricky

import sys,time

for  i in range(20):
    sys.stdout.write ( "#")                 # 用sys模块  标准输出,写。
    sys.stdout.flush()                      # 时时刷新
    time.sleep(0.1)                         # 使用time模块。延时

 

truncate

截断

我们现在有这个一个文件,

[root@localhost day3]# cat yesterday2.txt 
When I was young
当我小时候
I'd listen to the radio
聆听收音机
Waitng for my favorite songs
等着我最喜欢的歌曲
When they played I'd sing along
当歌曲播放时我和着它轻轻吟唱
[root@localhost day3]# cat file_op.py #!/usr/bin/env python3 f = open ("yesterday2.txt",'a') f.truncate() # 直接使用的话,看不出效果,因为没有指定从哪里截断。 [root@localhost day3]# ./file_op.py [root@localhost day3]# [root@localhost day3]# cat yesterday2.txt When I was young 当我小时候 I'd listen to the radio 聆听收音机 Waitng for my favorite songs 等着我最喜欢的歌曲 When they played I'd sing along 当歌曲播放时我和着它轻轻吟唱

 

 

 

这边输入数字, 从哪个字段开始截断

[root@localhost day3]# cat yesterday2.txt 
When I was young
当我小时候
I'd listen to the radio
聆听收音机
Waitng for my favorite songs
等着我最喜欢的歌曲
When they played I'd sing along
当歌曲播放时我和着它轻轻吟唱
[root@localhost day3]# cat file_op.py 
#!/usr/bin/env python3

f = open ("yesterday2.txt",'a')
f.truncate(10)                                #从第10个字段开始截断 

[root@localhost day3]# ./file_op.py 
[root@localhost day3]# 
[root@localhost day3]# 
[root@localhost day3]# cat yesterday2.txt 
When I was[root@localhost day3]# 

 

 

和seek配合,可以指定删除的范围

以下从第10个字符开始算。往后截取10个字符。 后面的截断。  其实就是保留了 20个字符

[root@localhost day3]# cat yesterday2.txt 
When I was young
当我小时候
I'd listen to the radio
聆听收音机
Waitng for my favorite songs
等着我最喜欢的歌曲
When they played I'd sing along
当歌曲播放时我和着它轻轻吟唱
It made me smile
我脸上洋溢着幸福的微笑


[root@localhost day3]# cat file_op.py 
#!/usr/bin/env python3

f = open ("yesterday2.txt",'a')   
f.seek(10) 
f.truncate(20)

[root@localhost day3]# 
[root@localhost day3]# ./file_op.py 
[root@localhost day3]#
[root@localhost day3]# cat yesterday2.txt                      #保留了20个字符
When I was young
当[root@localhost day3]# 

 

 

读写  r+

可以用于打开文件,然后追加内容。

通过以下我们可以看到。他是写在最后一行的 。可以同时读和写。

[root@localhost day3]# cat yesterday2.txt 
所有我喜爱万分的歌曲
Every shalala every wo'wo
每一个shalala每一个wo‘wo
still shines
仍然光芒四射
Every shing-a-ling-a-ling
每一个shing-a-ling
that they're starting to sing
每一个他们开始唱的
so fine
都如此悦耳
Wen they get to the part
当他们唱到他
[root@localhost day3]# cat file_op.py 
#!/usr/bin/env python3

f = open ("yesterday2.txt",'r+')

print  ( f.readline() )
print  ( f.readline() )
print  ( f.readline() )
f.write("=========")
print  ( f.readline() )

[root@localhost day3]# ./file_op.py 
所有我喜爱万分的歌曲

Every shalala every wo'wo

每一个shalala每一个wo‘wo


[root@localhost day3]# cat yesterday2.txt 
所有我喜爱万分的歌曲
Every shalala every wo'wo
每一个shalala每一个wo‘wo
still shines
仍然光芒四射
Every shing-a-ling-a-ling
每一个shing-a-ling
that they're starting to sing
每一个他们开始唱的
so fine
都如此悦耳
Wen they get to the part
当他们唱到他
=========[root@localhost day3]# 

 

写读 r+

貌似实际场景中用的不多。

他是先写再读,但是此处需注意。 他会将原有的文件先清空在重新开始写的 。然后才能读。

 

[root@master day3]# cat yesterday2.txt 
seems the love I've known,
看起来我所知道的爱情
has always been the most destructive kind.
好像总是变成破坏性的那种
I guess that's why now I feel so old before my time.
我猜这就是为什么我感到如此苍老,比起我的真实年龄
Yesterday When I was young
往日当我还年轻时
The taste of life was sweet
生命的感受如此美好
[root@master day3]# cat file_op.py 

#!/usr/bin/env python3 f = open("yesterday2.txt","w+") f.write("---------dao1-----------\n") f.write("---------dao2-----------\n") f.write("---------dao3-----------\n") f.write("---------dao4-----------\n") f.seek(0) #回到第一个字符,开始读,因为写的时候,其实已经在最后一个字符串了 print (f.readline()) print (f.readline()) f.close() [root@master day3]# ./file_op.py ---------dao1----------- ---------dao2----------- [root@master day3]# [root@master day3]# cat yesterday2.txt ---------dao1----------- ---------dao2----------- ---------dao3----------- ---------dao4-----------

 

rb 读取2进制的文件

查看一下。可以看在用2进制的方式读取文件。 前面会有b开头(binary)

linux上处理

[root@master day3]# cat yesterday2.txt 
---------dao1-----------
---------dao2-----------
---------dao3-----------
---------dao4-----------
[root@master day3]# cat file_op.py 
#!/usr/bin/env  python3
f = open("yesterday2.txt","rb") print (f.read()) f.close()

[root@master day3]# ./file_op.py b'---------dao1-----------\n---------dao2-----------\n---------dao3-----------\n---------dao4-----------\n'

 

 

windows上处理

需注意,因为之前windows上面有encoding编码的。 如果直接用2进制打开会报错。

 

 

 

 所以在windows上面需要用2进制的话,需要将encoding去掉,就可以了。

 

 

 

wb

2进制写。

[root@master day3]# cat file_op.py 
#!/usr/bin/env  python3


f = open("yesterday2.txt","wb")


f.write( "hello binary".encode())            #需要将字符串转换成2进制

f.close()


[root@master day3]# ./file_op.py 
[root@master day3]# cat yesterday2.txt 
hello binary[root@master day3]# 

 

 

 

修改文件中内容

要修改文件中的内容,其实只有2中方法。

1.打开文件,加载在内存中,进行修改,在保存在磁盘中, 就像 vim 这种的。

2. 读取老文件,进行修改,然后弄到新文件。

[root@localhost day3]# cat yesterday2.txt 
When I was young
当我小时候
I'd listen to the radio
聆听收音机
Waitng for my favorite songs
等着我最喜欢的歌曲
[root@localhost day3]# cat file_op.py 
#!/usr/bin/env python3

f = open ("yesterday2.txt",'r')
f_new = open ("yesterday2.new",'w')

for  line  in  f:
	if "I'd listen to the radio"  in line:
		line = line.replace("I'd listen to the radio","I'd  watch the television")              # 使用字符串替换, 替换需要修改的字符串
	f_new.write(line)

f.close()
f_new.close()

[root@localhost day3]# ./file_op.py 
[root@localhost day3]# ls
file_op.py  yesterday2.new  yesterday2.txt  yesterday.txt
[root@localhost day3]# cat yesterday2.new 
When I was young
当我小时候
I'd  watch the television
聆听收音机
Waitng for my favorite songs
等着我最喜欢的歌曲

 

 

 

 

for循环,  可以做如下理解。就是不管是不是判断到  字符串是否有进行替换, 都会写。

for  line  in  f:
	if "I'd listen to the radio"  in line:                                                   
		line = line.replace("I'd listen to the radio","I'd  watch the television")                    
	f_new.write(line)


其实等于

for line in f:
    if "I'd listen to the radio"  in line:
        line = line.replace("I'd listen to the radio","I'd  watch the television")
        f_new.write(line)
    else:
        f_new.write(line)

 

 

with  语句

我们常常会忘记关闭文件。 with可以帮助我们关闭文件

格式

with open( "yesterday2",'r',encoding="utf-8") as  f :
    for line  in f:
        print( line )

 

 

其实就是将写变量的形式 改了。    然后这个就不用为close  担心了。

 

f = open( "yesterday2",'r',encoding="utf-8")

改

with open( "yesterday2",'r',encoding="utf-8") as  f :

 

同时  可以打开多个

with open( "yesterday2",'r',encoding="utf-8") as  f , open( "yesterday3",'r',encoding="utf-8") as  g :
    for line  in f:
        print( line )

 

可以写的工整点

with open( "yesterday2",'r',encoding="utf-8") as  f , \
     open( "yesterday3",'r',encoding="utf-8") as  g :
    for line  in f:
        print( line 

 

 

 

函数 和    函数式编程

面向对象

 主要方式 是 类  ---》 class

面向过程

 主要方式是  过程---》 def

函数式编程

主要方式   函数  ---》  def

 

格式

#  函数式编程
def func1():                                       # 定义函数
    '''testing 111 '''                             # 注释
    print ("in the func1")                         # 函数内容
    return 0                                       #  返回值

#  面向过程     和函数式相比就少了个 返回值。过程就像没有返回值的函数
def func2():
    '''testing  222'''
    print ("in the func2")

 

 

关于return 的 总结:

 

1.没有返回值。 返回 none

2.返回值=0, 返回object(对象)

3.返回值>0, 返回tuple(元组)

 

root@localhost day3]# ./func.py 
in the func1
in the func2
in the func3
None
0
(0, 'aaa', ['aaa', 'bbb'], {'aaa': 'bbb'})
[root@localhost day3]# clear
[root@localhost day3]# lsc
-bash: lsc: command not found
[root@localhost day3]# clear
[root@localhost day3]# cat func.py 
#!/usr/bin/env  python3

def func1():
    '''testing 111 '''
    print ("in the func1")

def  func2():
    ''' testing222'''
    print ("in the func2")
    return 0

def func3():
    '''testing333'''
    print ('in the func3')
    return 0 ,('aaa'), ['aaa','bbb'],{'aaa':'bbb'}

a = func1()
b = func2()
c = func3()

print (a)
print (b)
print (c)

[root@localhost day3]# ./func.py 
in the func1
in the func2
in the func3
None
0
(0, 'aaa', ['aaa', 'bbb'], {'aaa': 'bbb'})
[root@localhost day3]# 

 

 

函数赋值

 

位置参数

可以给函数赋值, 但是当运行函数的时候,一定要把值写进去。否则会报错

[root@localhost day3]# cat func.py 
#!/usr/bin/env  python3

def func1(x,y):                    # 这里的x y 叫形参
    '''testing 111 '''
    print ( x )
    print ( y )
    return 0 

func1  (1,2)                       # 这里的x y 叫实参,顺序于形参一一对应
[root@localhost day3]# ./func.py 1 2

 

 

关键字调用

也可以这么写

[root@localhost day3]# cat func.py 
#!/usr/bin/env  python3

def func1(x,y):
    '''testing 111 '''
    print ( x )
    print ( y )
    return 0 

func1  (y=2,x=1)                                 # 这个叫关键字调用             

[root@localhost day3]# ./func.py 
1
2

 

有可以2者混用

这边有个地方需要注意, 就是位置参数一定要写在关键字参数的前面, 否则会报错 。

[root@localhost day3]# cat func.py 
#!/usr/bin/env  python3

def func1(x,y,z):
    '''testing 111 '''
    print ( x )
    print ( y )
    print ( z )
    return 0 

func1  (2,z=1,y=6)

[root@localhost day3]# ./func.py 
2
6
1

 

 

默认参数

就是形参的时候,直接就给赋值了。 

特点:

1.调用函数的时候,默认参数非必须传递。  可用于,安装时候的默认安装

[root@localhost day3]# cat  func.py 
#!/usr/bin/env  python3

def func1(x,y=2):
    '''testing 111 '''
    print ( x )
    print ( y )
    return 0 

func1  (4)

[root@localhost day3]# ./func.py 
4
2

 

参数组

 

当实参的数量确定不了的时候。  我们可以使用参数组。 这样就不会报错 了。

可以接受N个 位置参数。转换成元组的形式。

def func1(*args):
    '''testing 111 '''
    print (args)

func1(1,2,3,4,5,6)

 

字典形式传参

**kwagrs : 把N个关键字参数,转换成字典的方式。

[root@localhost day3]# cat func.py 
#!/usr/bin/env  python3

def func1(**kwargs):                          #固定格式  
    '''testing 111 '''
    print (kwargs)

func1  ( name = 'alex', age = '11' , sex = 'f' )

[root@localhost day3]# ./func.py 
{'name': 'alex', 'age': '11', 'sex': 'f'}

 

 

也可以单独把 当个元素 取出来。

[root@localhost day3]# cat func.py 
#!/usr/bin/env  python3

def func1(**kwargs):
    '''testing 111 '''
    print (kwargs)
    print (kwargs['name'])
    print (kwargs['age'])
    print (kwargs['sex'])

func1  ( name = 'alex', age = '11' , sex = 'f' )

[root@localhost day3]# ./func.py 
{'name': 'alex', 'age': '11', 'sex': 'f'}
alex
11
f

 

也可以和  其他参数一起使用

[root@localhost day3]# cat func.py 
#!/usr/bin/env  python3

def func1(name,age=18,**kwargs):     #和默认参数,位置参数一起使用
    '''testing 111 '''
    print (name)
    print (age)
    print (kwargs)

func1  ( 'AAAA', hobby = 'hahaha' , sex = 'f' )


[root@localhost day3]# ./func.py 
AAAA
18
{'hobby': 'hahaha', 'sex': 'f'}        #将关键字参数变成了字典的形式

 

函数套 函数

[root@localhost day3]# cat func.py 
#!/usr/bin/env  python3

def  logger (source):
   print ("from  %s" %source )      
 
def func1(name,age=18,**kwargs):
    '''testing 111 '''
    print (name)
    print (age)
    print (kwargs)
    logger ("test4")                                      # 函数套函数 

func1  ( 'AAAA', hobby = 'hahaha' , sex = 'f' )


[root@localhost day3]# ./func.py 
AAAA
18
{'hobby': 'hahaha', 'sex': 'f'}
from  test4

 

 

 

局部变量

就是将一个变量封在函数中, 而不影响全局变量

在子程序中定义的变量称为局部变量 。在程序的一开始定义的变量称为全局变量。

全局变量的作用域是整个程序,局部变量的作用域是定义改变量的子程序。

当全局变量和局部变量同名的时候:

在定于局部变量的子程序内,局部变量起作用,其他地方全局变量起作用。

[root@localhost day3]# cat  func.py 
#!/usr/bin/env  python3


def  change_name(name):
      print  ("before name",name)
      name  = "BBBB"                              #这函数就是这个这个变量的作用域,只在函数里面生效 
      print  ("after name", name)

name = "aaaa"
print(name)
change_name(name)
print(name)

 
[root@localhost day3]# ./func.py 
aaaa                                         #函数外
before name aaaa                             #函数内
after name BBBB                              #函数内
aaaa                                         #函数外

 

函数中定义全局变量

上面我们看到,函数中变量值能在函数中生效。  但是如果我们要强行在函数中定义全局变量,也能实现。

 

使用global

[root@localhost day3]# cat func.py 
#!/usr/bin/env  python3


country =  "china"

def  change():
     global country
     country = "USA"
     print  (country)

print (country)
change()
print( country )
[root@localhost day3]# ./func.py 
china
USA
USA

 

 

但是这里我们要注意一个问题。  如果我们要在函数中定义全局变量。   则在定义之前。我们不能在函数中调用这个变量 ,否则会报错 。如下 。

在定义global之前,就使用这个变量了。

 

 

 然后运行的时候回报错。

 

所以在函数中使用全局变量。 在定义前。不能使用

 

 

局部变量中的,列表、字典等复杂变量可以全局生效。

[root@localhost day3]# cat func.py 
#!/usr/bin/env  python3


name  = [ 'aaa','bbb','ccc']

def change_name():
    print (  "inside", name )
    name[0] = ('11111')

change_name()
print (name)


[root@localhost day3]# ./func.py 
inside ['aaa', 'bbb', 'ccc']
['11111', 'bbb', 'ccc']

 

 

 

递归 

就是自己调用自己

[root@localhost day3]# cat recursion.py 
#!/usr/bin/env  python3



def calc (n):
    print(n)
    return calc(n+1)                                #返回的 调用自己的函数,是自己的函数+1

calc(0)
[root@localhost day3]# ./recursion.py  
0
1
2

 

调用的函数 最多只有 999层。之后就会报错了

 

递归的特性:

1. 必须有一个明确的结束条件

2.每次进入更深一层递归时,问题的规模比上次递归的应有所较少。

3.递归的效率不高,递归的层次过多会导致栈溢出。

 

以下递归是,给他一个值。并且一直除以2,并且保持整数的情况下,要大于0,才执行。

[root@localhost day3]# cat recursion.py 
#!/usr/bin/env  python3


def calc (n):
    print(n)
    if int(n) > 0:
        return  calc(int(n/2))
calc(10)

[root@localhost day3]# ./recursion.py 
10
5
2
1
0

 

 

高阶函数(此处可以和day4的 装饰器 一起看 , 有助于理解 )

函数里面可以有参数。如果一个函数里面接受另一个函数作为参数,那这种函数就是高阶函数。

1.  把一个函数名当做实参传给另一个函数

2. 返回值中包含函数名

[root@localhost day3]# cat func.py 
#!/usr/bin/env  python3


def add (a,b,f):
    return f(a) + f(b)


res = add(3,-6,abs)                                  #abs其实是内置函数(这样就是函数调函数), 是取绝对值的意思(就是都是正数)本来是(-6+3)应该等于-3. 但是都是绝对值的话就是(6+3)。那就是9,
#  此处需要注意,这边是传函数,不是传函数的执行结果,所有不能abs()这么写
print(res) [root@localhost day3]# ./func.py 9

 

 

匿名函数

就是不用定义名字的函数、使用lambda函数

[root@localhost day4]# cat decorator1.py 
#!/usr/bin/env  python3

calc = lambda x:x*3
print  ( calc (3))


[root@localhost day4]# ./decorator1.py 
9

 

转载于:https://www.cnblogs.com/rockyricky/p/10857671.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值