gpt4 book ai didi

Python 笛卡尔幂发生器在幂列表上

转载 作者:行者123 更新时间:2023-11-30 23:26:13 24 4
gpt4 key购买 nike

如何创建一个类似于由 itertools.product() 生成的 Python 生成器,但它会迭代重复值列表?它的行为就像这个嵌套的 for 循环:

theSet = 'ABC'
thePowers = range(4)

for i in thePowers:
for j in itertools.product(theSet, repeat=i):
print j

但我希望它是一个生成器,这样会产生相同的输出:

for p in myGenerator:
print p

最佳答案

你可以为它定义一个生成器函数..

>>> from itertools import product
>>> def my_gen(letters, powers):
... for power in powers:
... for cartesian in product(letters, repeat=power):
... yield cartesian
...
...
...
>>>

并像这样使用它:

>>> for p in my_gen("ABC", range(4)):
... print p
()
('A',)
('B',)
('C',)
('A', 'A')
('A', 'B')
('A', 'C')
('B', 'A')
('B', 'B')
('B', 'C')
('C', 'A')
('C', 'B')
('C', 'C')
('A', 'A', 'A')
('A', 'A', 'B')
('A', 'A', 'C')
('A', 'B', 'A')
('A', 'B', 'B')
('A', 'B', 'C')
('A', 'C', 'A')
('A', 'C', 'B')
('A', 'C', 'C')
('B', 'A', 'A')
('B', 'A', 'B')
('B', 'A', 'C')
('B', 'B', 'A')
('B', 'B', 'B')
('B', 'B', 'C')
('B', 'C', 'A')
('B', 'C', 'B')
('B', 'C', 'C')
('C', 'A', 'A')
('C', 'A', 'B')
('C', 'A', 'C')
('C', 'B', 'A')
('C', 'B', 'B')
('C', 'B', 'C')
('C', 'C', 'A')
('C', 'C', 'B')
('C', 'C', 'C')

您还可以使用生成器表达式!

>>> products = list(product("ABC", repeat=i) for i in range(4))
>>> result = list(x for lst in products for x in lst)
>>> result
[(), ('A',), ('B',), ('C',), ('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'A'), ('B
', 'B'), ('B', 'C'), ('C', 'A'), ('C', 'B'), ('C', 'C'), ('A', 'A', 'A'), ('A',
'A', 'B'), ('A', 'A', 'C'), ('A', 'B', 'A'), ('A', 'B', 'B'), ('A', 'B', 'C'), (
'A', 'C', 'A'), ('A', 'C', 'B'), ('A', 'C', 'C'), ('B', 'A', 'A'), ('B', 'A', 'B
'), ('B', 'A', 'C'), ('B', 'B', 'A'), ('B', 'B', 'B'), ('B', 'B', 'C'), ('B', 'C
', 'A'), ('B', 'C', 'B'), ('B', 'C', 'C'), ('C', 'A', 'A'), ('C', 'A', 'B'), ('C
', 'A', 'C'), ('C', 'B', 'A'), ('C', 'B', 'B'), ('C', 'B', 'C'), ('C', 'C', 'A')
, ('C', 'C', 'B'), ('C', 'C', 'C')]

关于Python 笛卡尔幂发生器在幂列表上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22647898/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com