3.1. dictionary generative, set generative, and generator, 3.1 generative
Dictionary generation:
- Like the list generator, the dictionary generator is used to quickly generate a dictionary. The difference is that the dictionary requires two values.
#d = {key: value for (key, value) in iterable}d1 = {'x': 1, 'y': 2, 'z': 3}d2 = {k: v for (k, v) in d1.items()}print(d2)
Set generation formula:
- The Set generative format is similar to the list generative format, but braces are used:
s1={x for x in range(10)}print(s1)
Generator:
- A generator is an iterative process that generates the iteratable objects of corresponding elements.
- The generator element is not generated before access. It is generated only when access is made. If backward access is continued, the current element is destroyed.
- One way to generate a builder is to change the list generative form to parentheses:
Print ("----- generate generator using the () list generator ------") g = (x * x for x in range (10) print (type (g), g) print (next (g), next (g), next (g ))
- A generator is essentially a function.
- When a generator is called, it returns a generator object without executing the function. When the first call
next()
Method, the function is executed downward. If yield is encountered, the system returnsAfter yield
Value. Call againnext()
Method, the function continues to run down from the last point. If yield is encounteredAfter yield
Value.
- You can use yield to define a generator:
Print ("\ n ---- generate generator -------" Using yield) def ge (): print ("first yield") yield 1 print ("second yield ") yield 2 print ("third yield") yield 3o = ge () print (next (o )) ----------------- run result: ---- use yield to generate generator ------- the first yield1 the second yield2 the third yield3
- The generator is essentially a function. To obtain the return value of this function, we need to use exception capture to obtain the return value:
Def fib (max): n, a, B = 0, 0, 1 while n <max: yield B a, B = B, a + B n = n + 1 return 'done' print ("\ n ----- try to get function return value ------") gg = fib (6) while True: try: x = next (gg) print ("g:", x) expect t StopIteration as e: print ('Return value equals: ', e. value) break
- You can use next () for iteration generator or for iteration:
Def ge (): print ("first yield") yield 1 print ("second yield") yield 2 print ("third yield") yield 3o = ge () print ("\ n --- iterative generator method --------") for x in o: print (x) # equivalent to entering the generator function, execute it, and get the returned value ---- result: --- iterative generator method -------- first yield1 second yield2 third yield3
- Due to the features of the generator, you can perform the "coroutine" Operation: To be supplemented later