预计阅读本页时间:-
Generator Functions Versus Generator Expressions
Interestingly, the same iteration can often be coded with either a generator function or a generator expression. The following generator expression, for example, repeats each character in a string four times:
>>> G = (c * 4 for c in 'SPAM') # Generator expression
>>> list(G) # Force generator to produce all results
['SSSS', 'PPPP', 'AAAA', 'MMMM']
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
The equivalent generator function requires slightly more code, but as a multistatement function it will be able to code more logic and use more state information if needed:
>>> def timesfour(S): # Generator function
... for c in S:
... yield c * 4
...
>>> G = timesfour('spam')
>>> list(G) # Iterate automatically
['ssss', 'pppp', 'aaaa', 'mmmm']
Both expressions and functions support both automatic and manual iteration—the prior list call iterates automatically, and the following iterate manually:
>>> G = (c * 4 for c in 'SPAM')
>>> I = iter(G) # Iterate manually
>>> next(I)
'SSSS'
>>> next(I)
'PPPP'
>>> G = timesfour('spam')
>>> I = iter(G)
>>> next(I)
'ssss'
>>> next(I)
'pppp'
Notice that we make new generators here to iterate again—as explained in the next section, generators are one-shot iterators.