Python [5]-generative, generator, and python generative
I. Condition and loop 1. if statement
If <condition judgment 1>: <execution 1> elif <condition Judgment 2>: <execution 2> else: <execution 4>
For example:
age=5if age>=18: print 'adult'elif age>=6: print 'teenager'else: print 'kid'
Be sure to pay attention to the colon at the end of the Condition Statement and the indentation of the code segment.
As long as the if parameter is a non-zero value, non-empty string, non-empty list, etc., it is determinedTrue
OtherwiseFalse
.
2. Loop
Range (num): Returns an integer between 0 and num-1. For example:
print range(5)>>>[0,1,2,3,4]
For Loop:for x in ...
A loop is to substitute each element into a variable.x
And then execute the indent BLOCK statement.
s=0for i in range(101): s+=iprint s
WhileLoop: as long as the conditions are met, the loop continues. If the conditions are not met, the loop exits.
i=1s=0while(i<=100): s=s+i i=i+1print s
3. Iteration
Dict typeFor... in ..Iterations can be performed in the following ways:
D = {'A': 1, 'B': 2, 'C': 3}
Default iteration key
for k in d: print k
Iterkeys () returns the key iterator
for key in d.iterkeys(): print key
Itervalues () returns the value iterator
for value in d.itervalues(): print value
Iteritems () Return key-Value Pair iterator
for key,value in d.iteritems(): print key+"="+str(value)
Determine whether objects can be iterated: Through the collections ModuleIterableType Determination
from collections import Iterableprint isinstance(d,Iterable)
Iteration with Subscript: Python built-inenumerate
A function can convert a list into an index-element pair.
l=range(5)for i,value in enumerate(l):print i,value
Ii. generative method 1. List generative Method
The list generator is one of python's popular syntaxes. A Concise syntax can be used to filter a group of elements and convert the elements. Syntax format:
[exp for val in collection if condition]
Equivalent
result=[]for val in collection: if(condition): result.append(exp)
Let's take an example: Convert the strings in the list to lowercase to form a new list.
L = ['hello', 10, 'World', None] print [s. lower () for s in L if isinstance (s, str)] running result: ['hello', 'World']
2. dictionary generative
The basic dictionary generative format is as follows:
{key-exp:val-exp for value in collection if condition}
For example:
Print {I: I * 10 for I in range () if (I % 2 = 0)} running result: {8: 80, 2: 20, 4: 40, 6: 60}
3. Set generative Formula
The format of the Set generative type is similar to that of the List generative type, but braces are used:
{exp for value in collection if condition}
For example, the length of the string element in the statistics list.
L = ['hello', 10, 'World', None, 'a'] print {len (x) for x in L if isinstance (x, str)} running result: set ([2, 5])
4. nested list generator
Note the order of the for loop when generating nested lists.
For example, we want to extract a string containing a from a nested list composed of two lists:
L1 = [['Cathy ', 'lil'], ['zhang', 'wang ', 'Mike', 'Tom ', 'jack'] print [name for list in L1 for name in list if name. count ('A')> 0] running result: ['Cathy ', 'zhang', 'wang ', 'jack']
We can also flat the data in the nested list, for example:
L2 = [(100,200, 5), (, 6), ()] print [value for t in L2 for value in t] running result: [1, 3, 5, 2, 4, 6,100,200]
The syntax is too concise !!
Iii. Generator
In Python, a custom iterator is called a Generator ).
Two methods to define a generator:
1. To create a generator, you only need to generate a list[]
Change()
, A generator is created:
L = [x for x in range (1, 10)] print lg = (x for x in range (1, 10) print g. next () print g. next () for x in g: print x running result: [1, 2, 3, 4, 5, 6, 7, 8, 9] 123456789
Generator stores algorithms and calls them each time.next()
The value of the next element is calculated until the last element is computed and no more elements exist. The StopIteration error is thrown.
2. Define another method of generator. If a function definition containsyield
Keyword, so this function is no longer a common function, but a generator:
Def fib (n): a = 1 B = 1 I = 0; yield a yield B while (I <n): a, B = B, a + B I + = 1 yield bfor x in fib (10): print x running result: 1123581321345589144
Differences between generators and common functions:
Normal Functions are executed sequentially. If a return statement or the last function statement is returned;
The generator function is called every timenext()
When you runyield
Statement returned.yield
Statement.
Def test (): print 1 yield print 2 yield print 3 yieldt = test () t. next () # The running result is 1 TB. next () # running result 2 T. next () # result 3