python进阶----高阶函数,返回多值,集合set和三目,上下文管理器

来源:互联网 发布:无锡网络教育专升本 编辑:程序博客网 时间:2024/05/21 10:42

高阶函数(map,filter,reduce)

#map(function_to_apply, list_of_inputs)items=[1,2,3]squared =list (map(lambda x: x**2,items))for i in squared:print(i)def multiply(x):        return (x*x)def add(x):        return (x+x)funcs = [multiply, add]for i in range(5):    value = map(lambda x: x(i), funcs)    print(list(value)) #filter过滤列表中的元素,并且返回一个由所有符合要求的元素所构成的列表,符合要求即函数映射到该元素时返回值为True.number_list = range(-5, 5)less_than_zero = filter(lambda x: x < 0, number_list)print(list(less_than_zero))#reducefrom functools import reduceproduct =reduce((lambda x , y :x*y ),[1,2,3])print(product)

返回多值

#最著名的方法,是使用global关键字 不要试着使用这方法。重要的事情说三遍,不要试着使用这方法!def profile():    global name    global age    name = "Danny"    age = 30profile()print(name)print(age)#有些人试着在函数结束时,返回一个包含多个值的tuple(元组),list(列表)或者dict(字典),来解决这个问题。这是一种可行的方式,而且使用起来像一个黑魔法:def profile():    name = "Danny"    age = 30    #return name,age     return {'name':name,'age':age}    #return [name,age]    #return (name, age)profile_data = profile()#print(profile_data[0])#print(profile_data[1])print(profile_data['name'])print(profile_data['age'])

集合set和多三目运算

#set(集合)是一个非常有用的数据结构。它与列表(list)的行为类似,区别在于set不能包含重复的值some_list =['a','b','c','a','c','d']duplicates = set([x for x in some_list if some_list.count(x)>1])print(duplicates)#交集another_list = set(['a','b','c','f'])some_list =set(some_list)print(another_list.intersection(some_list))#差集print(another_list.difference(some_list))#也可以用{}符号来创建集合a_set = {1,2,3}print(type(a_set))#三元运算:三元运算符通常在Python里被称为条件表达式,这些表达式基于真(true)/假(false)的条件判断,在Python 2.4以上才有了三元操作。#如果条件为真,返回真 否则返回假#condition_is_true if condition else condition_is_falseis_fat = Truestate = "fat" if is_fat else "not fat"print(state)#(返回假,返回真)[真或假]#(if_test_is_false, if_test_is_true)[test]fitness = ('skinny','fat')[is_fat]print(fitness)

上下文管理器

import iowith open('mk.jpg','rb') as file:jpgdata = file.read()if jpgdata.startswith(b'\xff\xd8'):text = 'this is a jpeg file (%d bytes long )\n'else:text = 'this is a random file(%d bytes long)\n'with io.open('summary.txt','w',encoding='utf-8') as outf:outf.write(text % len(jpgdata))"""上下文管理器(Context managers)上下文管理器允许你在有需要的时候,精确地分配和释放资源。使用上下文管理器最广泛的案例就是with语句了。基于类的实现一个上下文管理器的类,最起码要定义__enter__和__exit__方法。"""class File(object):def __init__(self,filename,method):self.fileObject = open(filename,method)def __enter__(self):return self.fileObjectdef __exit__(self,type,vaue,traceback):self.fileObject.close()with File("summary.txt",'a') as outf:outf.write('\nhello')"""    with语句先暂存了File类的__exit__方法    然后它调用File类的__enter__方法    __enter__方法打开文件并返回给with语句    打开的文件句柄被传递给opened_file参数    我们使用.write()来写文件    with语句调用之前暂存的__exit__方法    __exit__方法关闭了文件"""#我们还没有谈到__exit__方法的这三个参数:type, value和traceback。#Python会将异常的type,value和traceback传递给__exit__方法。#它让__exit__方法来决定如何关闭文件以及是否需要其他步骤#处理异常with File("summary.txt",'a') as outf:outf.undefined_function('\nhello')"""    它把异常的type,value和traceback传递给__exit__方法    它让__exit__方法来处理异常    如果__exit__返回的是True,那么这个异常就被优雅地处理了。    如果__exit__返回的是True以外的任何东西,那么这个异常将被with语句抛出。"""class File(object):    def __init__(self, file_name, method):        self.file_obj = open(file_name, method)    def __enter__(self):        return self.file_obj    def __exit__(self, type, value, traceback):        print("Exception has been handled")        self.file_obj.close()        return Truewith File('demo.txt', 'w') as opened_file:    opened_file.undefined_function()





原创粉丝点击