Python生成器行为 [英] Python generator behaviour

查看:134
本文介绍了Python生成器行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 xrange(i,l))

输入:

2
aab
aac

现在 subs [0] subs [1] 给我相同的结果。

now both subs[0] and subs[1] give me same result.

print list(subs[0])
>>>['a','aa','aac','a','ac','c']
print list(subs[1])
>>>['a','aa','aac','a','ac','c']

list(subs [0]) 应该是 ['a','aa','aab','a','ab','b']

我模糊地理解为什么会这样。我该怎么做才能使 subs [0] subs [1] 实际上不同。

I vaguely understand why this is happening. What do I do to make subs[0] and subs[1] actually different.

注意:更改行

subs.append(S[i:j+1] for i in xrange(l) for j in xrange(i,l))

with

subs.append([S[i:j+1] for i in xrange(l) for j in xrange(i,l)])

不是一个选项

推荐答案

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


生成器表达式中使用的变量是在
时懒惰地评估为生成器对象调用 __ next __()方法(与普通生成器以相同的
方式)。但是,最左边的for子句是立即计算的
,因此在处理生成器
表达式的代码中的任何其他可能的错误之前,可以看到它产生的错误
。后续条款无法立即评估
,因为它们可能取决于之前的for循环。

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] ,此时 S 具有最新值。

您可以使用普通发电机代替。现在 ss 是本地的 subgen

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))

这篇关于Python生成器行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆