简体   繁体   English

Pythonic方式的递归发生器?

[英]Recursive generator in Pythonic way?

Below is a generator that can create all combinations made of one character from a number of strings: 下面是一个生成器,可以创建由多个字符串中的一个字符组成的所有组合:

('ab', 'cd', 'ef') => 'ace', 'acf', 'ade', 'adf', 'bce', 'bcf', 'bde', 'bdf'.

However, I wonder if this can be done in a more Pythonic. 但是,我想知道这是否可以在更多的Pythonic中完成。

# Example input data
t = ('ab', 'cd', 'ef')

# Recursive generator
def comb(t):
    if t:
        for c in t[0]:
            for s in comb(t[1:]):
                yield c + s 
    else:
        yield ''

# Test of generator
for r in comb(t):
    print(r)

You can use itertools.product : 您可以使用itertools.product

>>> from itertools import product
>>> lis = ('ab', 'cd', 'ef')
for p in product(*lis):
    print "".join(p)
...     
ace
acf
ade
adf
bce
bcf
bde
bdf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM