首页 文章 精选 留言 我的

精选列表

搜索[函数],共10000篇文章
优秀的个人博客,低调大师

python函数式编程之迭代器

什么是迭代器 顾名思义,就是更新换代的意思 python中的迭代器就是根据上一个结果生成下一个结果,一直循环往复不断重复的过程 迭代器有两个特点: 1.不断重复同一个过程 2.根据上一个结果生成下一个结果 迭代器的定义 先来看两个例子 代码一: while True: cmd = input("input your command: ").strip() print(cmd) 代码二: l1 = ["a", "b", "c", "d"] count = 0 while count < len(l1): print(l1[count]) count += 1 在代码一中,让用户不断输入命令,然后打印用户输入的命令,这是一个不断重复的过程,但是后一个结果跟前一个结果没有什么联系,所以代码一不是迭代器 在代码二中,先定义一个列表l1和count,在count的值小于列表l1的长度中,打印列表中count索引的值,然后count的值加1,这几行代码符合迭代器的定义 代码二的执行过程: 首先,打印列表l1中count索引的值,这是一个不断重复的过程 然后,每循环一次,count的值就在以前的基础上增加1,直到count的值等于列表l1的长度时,循环中止 所以代码一不是迭代器,代码二才是符后迭代器的定义标准 迭代器的作用 python中常见的数据类型包括字符串,列表,元组,字典,集合,文件 我们知道,python中的数据类型又分为有序和无序 对于有序数据类型,可以如上面的代码二所示,使用索引遍历有序数据类型中的元素 而对于无序数据类型,就不可以使用索引来遍历其中的元素了,此时可以使用for循环来遍历其中的元素 现在来看看for循环到底做了哪些事,可以取出无序数据类型中的元素 dic1 = {"a": 1, "b": 2, "c": 3, "d": 4, } for k in dic1: print(k) 执行上面的程序,可以打印出字典dic1中所有的键 实际上,python为了提供一种不依赖于索引的迭代方式,python会为一些对象内置__iter__方法 在python中,如果一个对象有__iter__方法,那么这个对象就是可迭代对象 执行obj.__iter__()方法得到的结果就是迭代器 所以python中的迭代器,都会有__iter__方法和__next__方法 以上面定义的dic1为例 dic1 = {"a": 1, "b": 2, "c": 3, "d": 4, } i = dic1.__iter__() # dic1.__iter__方法执行结果得到一个迭代器i print(i) # 打印迭代器,得到结果:<dict_keyiterator object at 0x0000000002DBD278> print(i.__next__()) # 执行迭代器i中的__next__方法,得到dic1中的一个元素,然后打印迭代出的元素 print(i.__next__()) # 再次执行迭代器的__next__方法,得到dic1的第二个元素,然后打印出来 print(i.__next__()) # 第三次执行迭代器的__next__方法,得到dic1的第三个元素,然后打印出来 由于python的字典是无序的数据类型,所以每次得到的dic1中的元素可能是不相同的 执行三次__next__方法,得到的结果如下 a b c 上面dic1的长度为4,如果执行5次__next__方法,会出错什么结果 dic1 = {"a": 1, "b": 2, "c": 3, "d": 4, } i = dic1.__iter__() print(i.__next__()) print(i.__next__()) print(i.__next__()) print(i.__next__()) print(i.__next__()) 程序执行结果 a File "D:\python3\lib\unittest\loader.py", line 153, in loadTestsFromName b module = __import__(module_name) c File "E:\python_learn\py_code\test.py", line 21, in <module> d print(i.__next__()) StopIteration 可以看到,python解释器在执行第五次__next__方法时,抛出了StopIteration的错误,这说明如果执行__next__方法的次数超出迭代器的长度时,python解释会抛出异常 迭代器的优缺点 迭代器的优点 1.提供一种不依赖于索引的取值方式 2.提供惰性计算,每执行一次__next__方法,只会从迭代器中取出一个值,不管这个数据长度有多大,使用迭代器取值时,每取出一个值,占用的内存空间都一个元素的大小,非常节省内存空间 迭代器的缺点 1.取值比较麻烦。如果想用迭代器的方式取出列表中的第三个值,必须调用三次__next__方法,才能取出第三个值,而前两次取出的值实际上是没有作用的 2.一次性的,只能向后迭代,不能回退。如果运行两次__next__方法后,就不可能回退再去了迭代器的第一个值 3.不能获取到迭代器的长度,只能不停执行__next__方法,直到出现StopIteration的提示,此时才能知道迭代器的长度 for循环的执行过程 定义一个列表,使用for循环遍历取出列表中的值 l1 = ['a', 'b', 'c', 'd'] for i in l1: print(i) 在for循环的执行过程中,实际上for循环是把in后面的对象执行__iter__方法,得到一个迭代器对象,然后不停执行迭代器对象中的__next__方法,得到元素,然后把迭代出来的元素赋值给i,再调用print方法打印元素i,直到for循环捕捉到StopIteration异常,结束循环,程序停止 类似于下面的代码 l1 = ['a', 'b', 'c', 'd'] obj = l1.__iter__() while True: try: i = obj.__next__() print(i) except StopIteration: break 判断一个对象是迭代器对象还是可迭代对象 只要一个对象有__iter__方法,这个对象就是可迭代对象 一个可迭代对象有__next__方法,这个对象就是迭代器对象 判断python中的字符串,列表,元组,字典和文件对象是否是可迭代对象和迭代器对象 示例代码 from collections import Iterable, Iterator s1 = "hello" l1 = ['a', 'b', 'c', 'd'] t1 = ('a', 'b', 'c', 'd') set1 = {'a', 'b', 'c', 'd'} dic1 = {"a": 1, "b": 2, "c": 3, "d": 4, } f1 = open("db.txt", "w", encoding="utf-8") print(isinstance(s1, Iterable)) print(isinstance(l1, Iterable)) print(isinstance(t1, Iterable)) print(isinstance(set1, Iterable)) print(isinstance(dic1, Iterable)) print(isinstance(f1, Iterable)) print("*" * 30) print(isinstance(s1, Iterator)) print(isinstance(l1, Iterator)) print(isinstance(t1, Iterator)) print(isinstance(set1, Iterator)) print(isinstance(dic1, Iterator)) print(isinstance(f1, Iterator)) 执行结果: True True True True True True ****************************** False False False False False True 从上面的例子,可以看出,字符串,列表,元组,集合,字典和文件都是可迭代对象,其中只有文件是迭代器对象 在上面,我们知道,使用for遍历对象中的值时,是把in后面的对象的变为可迭代对象,然后调用__next__方法取出对象中的元素 既然文件本身就是迭代器对象,那使用for循环获取文件的内容时,又是怎么做的呢 先打开一个文件,打印出这个文件对象,再调用文件对象的__iter__方法得到迭代器对象,判断两个对象是否是同一个对象 f1 = open("db.txt", encoding="utf-8") print(f1) obj = f1.__iter__() print(obj) print(obj is f1) 执行结果 <_io.TextIOWrapper name='db.txt' mode='r' encoding='utf-8'> <_io.TextIOWrapper name='db.txt' mode='r' encoding='utf-8'> True 得到结论: 如果一个对象可以被for循环迭代,则这个对象一定是可迭代对象 文件对象被执行__iter__方法,得到的结果仍然是一个迭代器对象

优秀的个人博客,低调大师

python内建函数(不完全)

各位还是参考官方文档吧,我这些是自己感觉重要和常用的 abs () all (iterable) 如果迭代序列中所有的元素都为真,或者迭代序列为空的时候返回 True 。等价于: def all (iterable): for element in iterable: if not element: return False return True all (iterable) 如果迭代序列中所有的元素都为真,返回 True 。等价于 def any (iterable): for element in iterable: if element: return True return False complex ()创建复数: >>> complex ( 1 , 2 ) ( 1 + 2j ) >>> complex ( 1 ) ( 1 + 0j ) delattr ( object , name) For example, delattr (x, 'foobar' ) is equivalent to del x.foobar. dict ()创建字典 dir () >>> import struct >>> dir () # show the names in the module namespace [ '__builtins__' , '__doc__' , '__name__' , 'struct' ] >>> dir (struct) # show the names in the struct module [ 'Struct' , '__builtins__' , '__doc__' , '__file__' , '__name__' , '__package__' , '_clearcache' , 'calcsize' , 'error' , 'pack' , 'pack_into' , 'unpack' , 'unpack_from' ] >>> class Shape( object ): def __dir__( self ): return [ 'area' , 'perimeter' , 'location' ] >>> s = Shape() >>> dir (s) [ 'area' , 'perimeter' , 'location' ] divmod (I,j)返回以商和余数组成的元祖: >>> divmod ( 10 , 3 ) ( 3 , 1 ) enumerate (sequence[, start = 0 ]) >>> seasons = [ 'Spring' , 'Summer' , 'Fall' , 'Winter' ] >>> list ( enumerate (seasons)) [( 0 , 'Spring' ), ( 1 , 'Summer' ), ( 2 , 'Fall' ), ( 3 , 'Winter' )] >>> list ( enumerate (seasons, start = 1 )) [( 1 , 'Spring' ), ( 2 , 'Summer' ), ( 3 , 'Fall' ), ( 4 , 'Winter' )] 其实也就等价于: def enumerate (sequence, start = 0 ): n = start for elem in sequence: yield n, elem n + = 1 eval (expression[, globals [, locals ]]) >>> x = 1 >>> print eval ( 'x+1' ) 2 filter (function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item foritem in iterable if item] if function is None . getattr ( object , name[, default]) For example, getattr (x, 'foobar' ) is equivalent to x.foobar. hasattr ( object , name) help ([ object ])¶ hex (x) 将整形x转化为 16 进制字符串,如果想要转化浮点型,可以使用 float . hex (x) id ( object ) 对象的内存地址 input ([prompt]) Equivalent to eval ( raw_input (prompt)). isinstance ( object , classinfo) issubclass ( class , classinfo) iter (o[, sentinel]) 迭代o,直到指和sentinel相等。例如:reads a file until the readline() method returns an empty string: with open ( 'mydata.txt' ) as fp: for line in iter (fp.readline, ''): process_line(line) map (function, iterable, ...) Apply function to every item of iterable and return a list of the results. max (iterable[, args...][, key]) min (iterable[, args...][, key]) next (iterator[, default]) oct (x) Convert an integer number (of any size) to an octal string. The result is a valid Python expression. open (name[, mode[, buffering]]) property ([fget[, fset[, fdel[, doc]]]]) class C( object ): def __init__( self ): self ._x = None def getx( self ): return self ._x def setx( self , value): self ._x = value def delx( self ): del self ._x x = property (getx, setx, delx, "I'm the 'x' property." ) 创建只读属性:这个属性的值就不能修改了 class Parrot( object ): def __init__( self ): self ._voltage = 100000 @property def voltage( self ): """Get the current voltage.""" return self ._voltage class C( object ): def __init__( self ): self ._x = None @property def x( self ): """I'm the 'x' property.""" return self ._x @x .setter def x( self , value): self ._x = value @x .deleter def x( self ): del self ._x range ([start], stop[, step]) >>> range ( 10 ) [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] >>> range ( 1 , 11 ) [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] >>> range ( 0 , 30 , 5 ) [ 0 , 5 , 10 , 15 , 20 , 25 ] >>> range ( 0 , 10 , 3 ) [ 0 , 3 , 6 , 9 ] >>> range ( 0 , - 10 , - 1 ) [ 0 , - 1 , - 2 , - 3 , - 4 , - 5 , - 6 , - 7 , - 8 , - 9 ] >>> range ( 0 ) [] >>> range ( 1 , 0 ) [] reduce (function, iterable[, initializer]) Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce ( lambda x, y: x + y, [ 1 , 2 , 3 , 4 , 5 ]) calculates (((( 1 + 2 ) + 3 ) + 4 ) + 5 ). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned. round (x[, n]) >>> round ( 1.12313 , 2 ) 1.12 slice ([start], stop[, step]) sorted (iterable[, cmp [, key[, reverse]]]) staticmethod (function) Return a static method for function. class C: @staticmethod def f(arg1, arg2, ...): ... sum (iterable[, start]) tuple ([iterable]) >>> tuple ( "ada" ) ( 'a' , 'd' , 'a' ) zip ([iterable, ...]) zip () in conjunction with the * operator can be used to unzip a list : >>> x = [ 1 , 2 , 3 ] >>> y = [ 4 , 5 , 6 ] >>> zipped = zip (x, y) >>> zipped [( 1 , 4 ), ( 2 , 5 ), ( 3 , 6 )] >>> x2, y2 = zip ( * zipped) >>> x = = list (x2) and y = = list (y2) True >>> float .fromhex( '0x3.a7p10' ) 3740.0 >>> lists = [[]] * 3 >>> lists [[], [], []] >>> lists[ 0 ].append( 3 ) >>> lists [[ 3 ], [ 3 ], [ 3 ]] >>> lists = [[] for i in range ( 3 )] >>> lists[ 0 ].append( 3 ) >>> lists[ 1 ].append( 5 ) >>> lists[ 2 ].append( 7 ) >>> lists [[ 3 ], [ 5 ], [ 7 ]] >>> "The sum of 1 + 2 is {0}" . format ( 1 + 2 ) 'The sum of 1 + 2 is 3' >>> "they're bill's friends from the UK" .title() "They'Re Bill'S Friends From The Uk" >>> print '%(language)s has %(number)03d quote types.' % \ ... { "language" : "Python" , "number" : 2 } Python has 002 quote types. >>> dishes = { 'eggs' : 2 , 'sausage' : 1 , 'bacon' : 1 , 'spam' : 500 } >>> keys = dishes.viewkeys() >>> values = dishes.viewvalues() >>> # iteration >>> n = 0 >>> for val in values: ... n + = val >>> print (n) 504 >>> # keys and values are iterated over in the same order >>> list (keys) [ 'eggs' , 'bacon' , 'sausage' , 'spam' ] >>> list (values) [ 2 , 1 , 1 , 500 ] >>> # view objects are dynamic and reflect dict changes >>> del dishes[ 'eggs' ] >>> del dishes[ 'sausage' ] >>> list (keys) [ 'spam' , 'bacon' ] >>> # set operations >>> keys & { 'eggs' , 'bacon' , 'salad' } { 'bacon' } >>> v = memoryview( 'abcefg' ) >>> v[ 1 ] 'b' >>> v[ - 1 ] 'g' >>> v[ 1 : 4 ] <memory at 0x77ab28 > >>> v[ 1 : 4 ].tobytes() 'bce' >>> data = bytearray( 'abcefg' ) >>> v = memoryview(data) >>> v.readonly False >>> v[ 0 ] = 'z' >>> data bytearray(b 'zbcefg' ) >>> v[ 1 : 4 ] = '123' >>> data bytearray(b 'z123fg' ) >>> v[ 2 ] = 'spam' Traceback (most recent call last): File "<stdin>" , line 1 , in <module> ValueError: cannot modify size of memoryview object >>> m = memoryview( "abc" ) >>> m.tobytes() 'abc' >>> memoryview( "abc" ).tolist() [ 97 , 98 , 99 ] ============================================================================== 本文转自被遗忘的博客园博客,原文链接:http://www.cnblogs.com/rollenholt/archive/2011/11/25/2263726.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

openstack Havana create instances 调用的函数

(Pdb) bt /usr/lib/python2.6/site-packages/eventlet/greenpool.py(80)_spawn_n_impl() -> func(*args, **kwargs) /usr/lib/python2.6/site-packages/nova/openstack/common/rpc/amqp.py(461)_process_data() -> **args) /usr/lib/python2.6/site-packages/nova/openstack/common/rpc/dispatcher.py(172)dispatch() -> result = getattr(proxyobj, method)(ctxt, **kwargs) /usr/lib/python2.6/site-packages/nova/exception.py(73)wrapped() -> return f(self, context, *args, **kw) /usr/lib/python2.6/site-packages/nova/compute/manager.py(229)decorated_function() -> return function(self, context, *args, **kwargs) /usr/lib/python2.6/site-packages/nova/compute/manager.py(294)decorated_function() -> function(self, context, *args, **kwargs) /usr/lib/python2.6/site-packages/nova/compute/manager.py(258)decorated_function() -> return function(self, context, *args, **kwargs) /usr/lib/python2.6/site-packages/nova/compute/manager.py(1613)run_instance() -> do_run_instance() /usr/lib/python2.6/site-packages/nova/openstack/common/lockutils.py(246)inner() -> return f(*args, **kwargs) /usr/lib/python2.6/site-packages/nova/compute/manager.py(1612)do_run_instance() -> legacy_bdm_in_spec) /usr/lib/python2.6/site-packages/nova/compute/manager.py(946)_run_instance() -> instance, image_meta, legacy_bdm_in_spec) /usr/lib/python2.6/site-packages/nova/compute/manager.py(1037)_build_instance() -> set_access_ip=set_access_ip) /usr/lib/python2.6/site-packages/nova/compute/manager.py(1407)_spawn() -> block_device_info) /usr/lib/python2.6/site-packages/nova/virt/libvirt/driver.py(2063)spawn() -> admin_pass=admin_password) /usr/lib/python2.6/site-packages/nova/virt/libvirt/driver.py(2381)_create_image() -> ephemeral_size=int(ephemeral_gb)) /usr/lib/python2.6/site-packages/nova/virt/libvirt/imagebackend.py(183)cache() -> *args, **kwargs) > /usr/lib/python2.6/site-packages/nova/virt/libvirt/imagebackend.py(316)create_image() -> prepare_template(target=base, max_size=size, *args, **kwargs) /usr/lib/python2.6/site-packages/nova/openstack/common/lockutils.py(246)inner()->None -> return f(*args, **kwargs) /usr/lib64/python2.6/contextlib.py(34)__exit__() -> self.gen.throw(type, value, traceback) /usr/lib/python2.6/site-packages/nova/openstack/common/lockutils.py(205)lock() -> yield lock /usr/lib/python2.6/site-packages/nova/openstack/common/lockutils.py(246)inner()->None -> return f(*args, **kwargs) /usr/lib/python2.6/site-packages/nova/virt/libvirt/imagebackend.py(164)call_if_not_exists() 本文转自 swq499809608 51CTO博客,原文链接:http://blog.51cto.com/swq499809608/1342070

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

用户登录
用户注册
修改密码
忘记密码