string s= ' hello ' into uppercase, and convert each character into a list element, i.e. [' H ', ' E ', ' l ', ' l ', ' O ']Normal Loop code:s= ' Hello ' l=[]for i in S: res=i.upper () l.append (res) print (l)List Parsing code:s= ' Hello ' res=[i.upper () for I in S]print (res)Simple code generation can be simplified by using list parsingList-Generated Description:Example:L=[1,31,73,84,57,22]print ([i-I in L if I >]) #l列表中大于50的元素生成一个新列表print ([i-I in L if I print ([I for I in L if i > I
In Python, this side-loop mechanism, called the generator:Conclusion: The generator is essentially a function, and unlike a function, it produces an object that does not execute code inside the function.1.1.List Builder List Builder: lists are directly generated numbers in memory and can be called at any timeThe tuple display type is the generator, which is store
continually returns the next value is called an iterator:Iterator.You can use isinstance () to determine whether an object is a Iterator object: Generators are Iterator objects, but list dict str , although iterable, they are not Iterator.Iterable, and so on into Iterator can use iter() the function: list dict str Generator In Python , a mechanism that loops one side of the computation, called the generator:generator.Create a generator: Th
({}, Iterator) false>>> isinstance (' abc ', Iterator) FalseGenerators are Iterator objects, but,, list dict str Though Iterable they are, they are not Iterator .Turn list , dict and str wait for the Iterable Iterator function to be used iter() :>>> Isinstance (ITER ([]), Iterator) true>>> isinstance (ITER (' abc '), Iterator) TrueSummaryAny object that can be used for for the loop is a Iterable type;All objects that can be used for next() functions are Iterator types, which represent a sequenc
List Builder# Common is the range () to create a list of numbers >>>[x*x for x in range (10)][0, 1, 4, 9, 16, 25, 36, 49, 64, 81]# back can also be added with a judgment statement >>>[ X*x for x in range (ten) if x%2 = = 0][0, 4, 16, 36, 64]# characters can also play this way >>> [M + N for m in ' ABC ' for n ' XYZ ' [' AX ', ' A Y ', ' AZ ', ' BX ', ' by ', ' BZ ', ' CX ', ' CY ', ' CZ '] Generator# Generator is to replace the [] list generator (),
# Editor: Shanlong l = [2, 3, 4, 5, 6,7 for in# get a new list L1, each element in the new list is the square of the value of each element in L /c6>printforif i > Max]# filter out values greater than 40 in L1 and sum print(sum (L1))Above, there's nothing to say#edited by: ShanlongShares = { 'IBM': 36.6, 'Lenovo': 27.3, 'Huawei': 40.3, 'Oldboy': 3.2, 'Ocean': 20.1}#question one: A list of stock names with a stock price greater than 30L = [i forIinchSharesifFloat (shares[i]) >30]
fact, rarely use next (), we directly with the For loop can traverse a generator, in fact, the internal implementation of the For loop is to call next ().
Generators can avoid unnecessary computations, improve performance, and save space for an infinite loop (infinitely large) data structure.
Builder syntaxGenerator expression: pass-through list parsing syntax, just replace the list parsing [] with ()The list of things that the
This article mainly describes the python in the iterator and the builder instance of the relevant information, the need for friends can refer to the following
An explanation of iterators and builder instances in Python
This paper summarizes some of the relevant knowledge of iterators and generators in
List parsing and builder expressions in PythonYun ZhengjieCopyright Notice: Original works, declined reprint! Otherwise, the legal liability will be investigated.I. List resolution CASES1 #! /usr/bin/env python2 #_*_coding:utf-8_*_3 #@author: Yinzhengjie4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%e8%87%aa%e5%8a%a8%e5%8c%96%e8%bf%90%e7%bb%b4%e4%b9%8b% e8%b7%af/5 #Email:[email protected]6 7Old ="Hel
( L) # Next essentially calls __next__print(L.__next__())Summarize:1: List-resolved [] replaced by () is the claim that its expression2: List parsing and builder expressions are all traversal programming, except that generator expressions are more memory-efficient3:python not only uses the iterator protocol, but makes the for loop more generic. Most built-in functions also use iterator protocols to acces
), and so on.Supplementary study: http://www.jianshu.com/p/d09778f4e055Generated: All data is generated at once and then stored in memory for small amounts of data.Generator: Returns an iterative object, the "Generator" object, which must be looped to list all the results.2. iteratorsThe main differences between iterable (iterative objects) and iterator (iterators) are:Anything that can be used for a loop is iterable (an iterative object) that can be called by loop, such as: [], (), {}, generati
First, the decoration device1, definition: The essence is the function, decorate other functions is to add the attachment function for other functions.2. Principle:A. Cannot modify the source code of the decorated function;B. Cannot modify the calling mode of the decorated function;Instance:#!/usr/bin/env python#-*-Coding:utf-8-*-#Author: YeImport time#装饰器def Time_cha (func): #func等于test Time_start = Time.time () Func () #此时func () equivalen
of the function. The function is executed sequentially, the return statement is encountered, or the last line function statement is returned. The function that becomes generator, executes at each invocation next() , encounters a yield statement return, and executes again from the last statement returned yield .1>>>def fibla (max):2... n,a,b =0,0,13... whileN Max:4...yieldb5... B = b,a+b6... n = n +17 ... 8>>> Fibla (8)9ObjectFibla at0x7f302fd5ca00>Ten>>> forXinchFibla (8): One ... print x A ...
() Step11>>>o.next () Step23>>>o.next () step35>>>O.next () Traceback (most recent): File"", Line 1,incho.next () stopiteration>>>As you can see, odd is not a normal function, but a generator, in the execution process, encounter yield is interrupted, the next time continue to execute. After 3 yield, no yield can be executed, so the 4th call to next () errorBack to the FIB example, we constantly call yield in the loop, and then we interrupt, of course, to set a condition for the loop to exit the
First, iterator iterators
An iterator is only a container object, and it implements the iterator protocol. It has two basic methods:
1) Next methodReturns the next element of a container
2) __iter__ methodReturns the iterator itself
Iterators can be created using the built-in ITER method, see examples:
Copy Code code as follows:
>>> i = ITER (' abc ')
>>> I.next ()
A
>>> I.next ()
' B '
>>> I.next ()
C
>>> I.next ()
Traceback (most recent call last):
File "St
()---------------------------------------------------------------------------Stopiteration Traceback (most recent)----> 1 G1.next ()Stopiteration:Returns the result of dividing the square of all positive integers in the range 1 to 10 by 2:In [all]: For I in (i**2 for I in range (1,11)):...: Print I/2...:0248121824324050To generate offsets and elements, use the Enumerate function:Range can be used to generate an index offset in a non-exhaustive traversal, not an element at the offsetIf you need
02, iterator Objects that can be iterated:Internal containing __iter__ follows an iterative protocol# Print (dir (' 123 ')) # ' __iter__ '# print (' __iter__ ' in Dir ([1, 2, 3])# Print (' __iter__ ' in dir ({' name ': ' Alex '})# print (' __iter__ ' in dir ({' name '})#) # Print (' __iter__ ' in Dir ((1, 2, 3))# print (' __iter__ ' in Dir (1)) # False# c15> print (' __iter__ ' in Dir (True)) # False iterator: An iterative object. __iter__ () can be converted to an iterator that sati
generate a value to return, and is dormant until the next call.
Builder (Generator)The generator is one of the most appealing features in the Python language, and the generator is actually a special iterator, but the iterator is more elegant. It does not need to write __iter__ () and __next__ () methods like the class above, but only one yiled keyword is required. The generator must be an iterator (not vi
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.