python - 跳过生成器函数中的值

标签 python generator

我正在编写一个生成器函数,它会给我字母字符,就像这样,

def gen_alphaLabels():
    a = range(65,91)
    for i in a:
        yield chr(i)

k = gen_alphaLabels()
for i in range(26):
    print k.next(),

这产生了,

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

这行得通....

我会跳过 donotInclude 列表中的一些字符。我可以在生成器外部执行此操作,就像这样,

k = gen_alphaLabels()
donotInclude = ['D','K','J']
for i in range(26):
    r = k.next()
    if r not in donotInclude:
        print r,

这会产生跳过“D”、“K”和“J”的预期结果

A B C E F G H I L M N O P Q R S T U V W X Y Z

有没有办法在生成器函数中包含与跳过字符相关的逻辑?一些事情沿着

def gen_alphaLabels():
    a = range(65,91)
    for i in a:
        r = chr(i)
        if r in donotInclude:
            yield self.next()
        else: 
            yield r

最佳答案

不使用 continue + 稍微缩短代码:

def gen_alphaLabels(donotInclude):
    for i in range(65,91):
        char = chr(i)
        if char not in donotInclude:
            yield char

关于python - 跳过生成器函数中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18620497/

相关文章:

Python的itertools乘积内存消耗

javascript - 当我每次函数调用创建一个新的生成器时,为什么这个生成器函数包装器会消耗迭代器?

python - shapefile中的图层是什么

python - 错误integerField django模型syncdb

python - 使用 Flexmock datetime.datetime.now 模拟

python - 在 Python 中的多个服务器(路由器)上运行命令(以备份配置)

generator - MobX 状态树生成器不允许修改成功 promise 中的状态?

python - 为什么发电机不能 pickle ?

python - 使用生成器从给定的单词造句

当我绘制x轴值时,Python seaborn线图是无序的(即使它们在数据框中按顺序排列)