python中show函数的⽤法_python学习笔记之——函数模块1、函数参数说明:
def login(name,info,passwd = '123456')
函数参数可以有默认值,调⽤函数时:
1、如果只传⼆个参数,则有默认值的⼀定要放到最后;
def login(name,passwd = '123456',info='welcome to you')
2、如果传⼆个参数,⼀定要指明形参;
login(user)
login(user,passwd)
login(user,info='欢迎')
login(user,info='欢迎',passwd='123456')
def login(*arg)      函数参数个数不定,传参数的时候可以多个,包装为列表;例:
def list_show(*args):
for name in args:
print(name)
list_show('a','b','c','d',1,2,3,4)      #传多个参数
list_show(['a','b','c',1,2,3])            #直接传个列表参数
def login(**arg)      函数参数个数不定,传参数的时候可以多个,包装为字典;例:
def dict_show(**args):
for name in args.items():import pickle
print(name)
dict_show(name='kevin',age=23)      #传多个参数时,格式为key=value
print('>>>###')
dict = {'name':'kevin','age':23}
dict_show(**dict)                  #直接传个字典参数时,字典前加⼆个**
2、⽣成器yield:
for i in range(1000): pass
会导致⽣成⼀个 1000 个元素的 List,⽽代码:for i in xrange(1000): pass
则不会⽣成⼀个 1000 个元素的 List,⽽是在每次迭代中返回下⼀个数值,内存空间占⽤很⼩。因为 xrange 不返回 List,⽽是返回⼀个iterable 对象。
同样类似于⽂件读⾏的readlines和xreadlines。
带有 yield 的函数在 Python 中被称之为 generator(⽣成器),例:
def kevin_readlines():
seek = 0
while True:
with open('D:/eclipse/workspace/python27/first_python27/','r') as f:
#with打开⽂件⽆需使⽤close来结束读取⽂件
f.seek(seek)
data =  f.readline()
if data:
seek = f.tell()
yield data
else:
return            #直接返回,退出函数
for line in kevin_readlines():
print(line)
yeild⽣成器需要⽤循环来⼀⾏⼀⾏读取。yeild经常⽤于读取函数的中间值,适合⽤于多线程之类的情况。使⽤next来⼀次⼀次调⽤函数值。
3、函数介绍:
★lamba
python lambda是在python中使⽤lambda来创建匿名函数,⽽⽤def创建的⽅法是有名称的,除了从表⾯上的⽅法名不⼀样外,python lambda还有哪些和def不⼀样呢?
1 python lambda会创建⼀个函数对象,但不会把这个函数对象赋给⼀个标识符,⽽def则会把函数对象赋值给⼀个变量。
2 python lambda它只是⼀个表达式,⽽def则是⼀个语句。
lambda语句中,冒号前是参数,可以有多个,⽤逗号隔开,冒号右边的返回值。lambda语句构建的其实是⼀个函数对象。
例:
m = lambda x,y,z: (x-y)*z
print m(234,122,5)
也经常⽤于⽣成列表,例:
list = [i ** i for i in range(10)]
print(list)
list_lambda = map(lambda x:x**x,range(10))
print(list_lambda)
★ enumerate(iterable,[start])  iterable为⼀个可迭代的对象;
enumerate(iterable[, start]) -> iterator for index, value of iterable Return an enumerate object.  iterable must be another object  that supports iteration.  The enumerate object yields pairs containing a count  (from start, which defaults to zero) and a value yielded by the iterable
argument. enumerate is useful for obtaining an indexed list:    (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
例:
for k,v in enumerate(['a','b','c',1,2,3],10):
print k,v
★S.format(*args, **kwargs) -> string  字符串的格式输出,类似于格式化输出%s
Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}').
s = 'i am {0},{1}'
print(s.format('wang',1))
★map(function,sequence) 将squence每⼀项做为参数传给函数,并返回值
例:
def add(arg):
return arg + 101
print(map(add,[12,23,34,56]))
★filter(function or None, sequence) -> list, tuple, or string  返还true的序列
Return those items of sequence for which function(item) is true.  If
function is None, return the items that are true.  If sequence is a tuple
or string, return the same type, else return a list.
例:
def comp(arg):
if arg < 8:
return True
else:
return False
print(filter(comp,[1,19,21,8,5]))
print(filter(lambda x:x % 2,[1,19,20,8,5]))
print(filter(lambda x:x % 2,(1,19,20,8,5)))
print(filter(lambda x:x > 'a','AbcdE'))
★reduce(function, sequence[, initial]) -> value  对⼆个参数进⾏计算
Apply a function of two arguments cumulatively to the items of a  sequence,
from left to right, so as to reduce the sequence to a single value.For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates((((1+2)+3)+4)+5).  If initial is present, it is placed before the
items of the sequence in the calculation, and serves as a default when  the sequence is empty.
例:
print(reduce(lambda x,y:x*y,[22,11,8]))
print(reduce(lambda x,y:x*y,[3],10))
print(reduce(lambda x,y:x*y,[],5))
★zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)] 将多个序列转化为新元祖的序列
Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences.  The returned list is  truncated in length to the length of the shortest argument sequence.
例:
a = [1,2,3,4,5,6]
b = [11,22,33,44,55]
c = [111,222,333,444]
print(zip(a,b,c))
★eval(source[, globals[, locals]]) -> value将表达式字符串执⾏为值,其中globals为全局命名空间,locals为局部命名空间,从指字的命名空间中执⾏表达式,
Evaluate the source in the context of globals and locals.    The source may be a string representing a
Python expression  or a code object as returned by compile().    The globals must be a dictionary and locals can be any mapping,    defaulting to the current globals and locals.    If only globals is given, locals defaults to it.
例:
a = '8*(8+20-5%12*23'
print(eval(a))
d = {'a':5,'b':4}
print(eval('a*b',d))
★exec(source[, globals[, locals]]) 语句⽤来执⾏储存在字符串或⽂件中的Python语句
例:
a = 'print("nihao")'
b = 'for i in range(10): print i'
exec(a)
exec(b)
★execfile(filename[, globals[, locals]])
Read and execute a Python script from a file.The globals and locals are dictionaries, defaulting to the currentglobals and locals.  If only globals is given, locals defaults to it.
4、常⽤模块:
★random ⽣成随机数
print random.random()            ⽣成0-1之间的⼩数
print random.randint(1,3)        ⽣成整数,包含endpoint
print random.randrange(1,3,2)    ⽣成整数,不包含endpoint
randrange(self, start, stop=None, step=?)
⽣成5位随机数,例:
import random
a = []
for i in range(5):
if i == random.randint(1,5):
a.append(str(i))
else:
a.append(chr(random.randint(65,90)))
else:
print(''.join(a))
★⽣成MD5码
例:
⼀. 使⽤md5包
import md5
src = 'this is a md5 test.'
m1 = w()
m1.update(src)
print m1.hexdigest()
⼆. 使⽤hashlib
import hashlib
hash = hashlib.md5()
hash.update('this is a md5 test.')
hash.update('admin')
print(hash.digest())
print(hash.hexdigest())
推荐使⽤第⼆种⽅法。
对以上代码的说明:
1.⾸先从python直接导⼊hashlib模块
2.调⽤hashlib⾥的md5()⽣成⼀个md5 hash对象
3.⽣成hash对象后,就可以⽤update⽅法对字符串进⾏md5加密的更新处理
4.继续调⽤update⽅法会在前⾯加密的基础上更新加密
5.加密后的⼆进制结果
6.⼗六进制结果
如果只需对⼀条字符串进⾏加密处理,也可以⽤⼀条语句的⽅式:
w("md5", "Nobody inspects the spammish repetition").hexdigest()) 5、python对象与⽂件之间的序列化和反序列化(pickle和json)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。

发表评论