目录
1. 函数
函数声明时使用def关键字
def add(x,y,z=0):
return x+y+z
#若在函数中没有使用return,那么函数将会自动返回None
#这里的x,y都是位置参数,z是关键字参数
#即调用函数时x,y必须传值,而z可以传也可以不传
a=add(1,1,z=2)
b=add(1,1,2)
c=add(x=1,y=1,z=2)
print('a:{0},b:{1},c:{2}'.format(a,b,c))
#输出:a:4,b:4,c:4
#可见,上面三种方式不同,但都是可以的
注意函数中变量的作用域
def link():
tmp_list=[]
tmp_list.append(1)
link()
print('content:{list}'.format(list=tmp_list))
'''
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[5], line 7
5 tmp_list.append(1)
6 link()
----> 7 print('content:{list}'.format(list=tmp_list))
NameError: name 'tmp_list' is not defined
'''
#此时的tmp_list只在函数有用,当函数结束时被销毁\
#解决方法:定义成全局变量
def link0():
global list0
#将list0定义为全局变量
list0=[]
list0.append(1)
link0()
print(list0)
#输出:[1]
1.1 Python的函数可以返回多个值
#相较于C++/C中的函数,Python的函数可以返回多个值
def output():
a=1;b=2;c=3
return {'a':a,'b':b,'c':c}
#返回了一个字典
output()
#输出:{'a': 1, 'b': 2, 'c': 3}
1.2 一个数据清理的例子
list1=['golden ', 'oh warriors', 'champi#onShip', 'Andrew wiggins', 'leo?']
#对这个字符串进行数据清理
#去除空格,移除标点,调整大小写
import re
#re是正则表达式模块
def clean_str(strings):
result=[]
for string in strings:
string=string.strip()
string=re.sub('[!#?]',' ',string)
string=string.title()
result.append(string)
return result
clean_str(list1)
#输出:['Golden', 'Oh Warriors', 'Champi Onship', 'Andrew Wiggins', 'Leo ']
1.3 lambda匿名函数
匿名函数是一种通过单个语句生成匿名函数的方式
lambda arguments(参数): expression(表达式)
比如:lambda x: x**2
等价于:def f(x):
return x**2
def apply_to_list(some_list,f):
return [f(x) for x in some_list]
#列表的推导式,不清楚的可以看这篇文章:http://t.csdnimg.cn/Lswfb
ints=[4,2,12,5,3]
#实现将列表中的每一个数平方
apply_to_list(ints,lambda x: x**2)
#输出:[16, 4, 144, 25, 9]
del list1
list1=['wiggins', 'Donic', 'James','aaaa']
list1.sort(key=lambda x:len(set(x)))
#按不同字母的数量对一个字符串集合排序,集合内的元素互异
list1
#输出:['aaaa', 'wiggins', 'Donic', 'James']
2. 文件操作函数
2.1 打开文件
在 Python中,如果想要操作文件,首先需要创建或者打开指定的文件,并创建一个文件对象,而这些工作可以通过内置的 open() 函数实现。
open() 函数支持的文件打开模式如表所示。
path = 'C:/Users/86183/Desktop/语言学习/python/Python数据分析/obj.txt'
f = open(path, 'w')
#默认情况下,文件是以只读模式打开的
f.write('Andrew Wiggins')
f.close()
#结束时必须要使用close函数,将资源释放回操作系统
使用with语句在代码块结束可以自动关闭文件
with open(path) as f:
lines=[x.rstrip() for x in f]
lines
#输出:['Andrew Wiggins']
2.2 读取文件
1.read方法通过读取字节数推进文件句柄位置。
f = open(path)
f.read(15)
#输出:'Andrew Wiggins'
f2=open(path,'rb')
#以二进制的形式打开
f2.read(15)
#输出:b'Andrew Wiggins '
2.tell方法可以给出当前句柄的位置
f.tell()
#输出:14
f2.tell()
#输出:14
3.seek方法可以将句柄的位置放到特定的字节
f.seek(3)
f.read(1)
#输出:‘r’
f.close()
f2.close()
4.readline和readlines函数
f = open(path)
f.readline()
#返回文件中行内容
#输出:'Andrew Wiggins is one of the best basketball player nowadays\n'
f.readlines()
#返回文件中行内容的列表
#输出:['But I wonder if the managerment of Warriors will let him go or not']
f.close()
f.closed
#判断是否关闭成功
#输出:True
参考书籍:《利用Python进行数据分析》Wes McKinney
参考文章: https://blog.51cto.com/u_14844/6663588
喜欢的小伙伴还请点赞收藏,(❁´◡`❁)( o=^•ェ•)o ┏━┓