Python generator behaviour

前端 未结 2 1492
广开言路
广开言路 2020-12-12 00:44
import itertools
ws=[]
subs=[]
set_subs=[]
for i in xrange(int(raw_input())):
    S=raw_input()
    l=len(S)
    subs.append(S[i:j+1] for i in xrange(l) for j in xra         


        
相关标签:
2条回答
  • 2020-12-12 01:00

    http://docs.python.org/reference/expressions.html#generator-expressions

    Variables used in the generator expression are evaluated lazily when the __next__() method is called for generator object (in the same fashion as normal generators). However, the leftmost for clause is immediately evaluated, so that an error produced by it can be seen before any other possible error in the code that handles the generator expression. Subsequent for clauses cannot be evaluated immediately since they may depend on the previous for loop.

    S[i:j+1] is evaluated when you execute the generator, and at that point S has the latest value.

    You can use a normal generator instead. Now ss is local to subgen:

    import itertools
    
    def subgen(ss):
        l=len(ss)
        for i in xrange(l):
            for j in xrange(i,l):
                yield ss[i:j+1]
    
    subs=[]
    for i in xrange(int(raw_input())):
        S=raw_input()
        subs.append(subgen(S))
    
    0 讨论(0)
  • 2020-12-12 01:09

    Well, this is one of the strange features of generator expression. Have a look at this In your case it is used late binding and that's why you will get two identical results.

    0 讨论(0)
提交回复
热议问题