Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python itertools生成具有替换的powerset_Python - Fatal编程技术网

Python itertools生成具有替换的powerset

Python itertools生成具有替换的powerset,python,Python,我正在尝试生成一个包含替换字符串的大型字符串列表的powerset。没有一个内置的itertools函数可以做到这一点(据我所知) 编辑可能在标题中使用“set”有误导性。这里的秩序很重要。”ca'!='ac' 我想要的示例: print( powerset_with_replacement(['abc']) ) # yeilds ('a',) ('b',) ('c',) ('a', 'a') ('a', 'b') ('a', 'c') ('b', 'b') ('b', 'c') ('c', '

我正在尝试生成一个包含替换字符串的大型字符串列表的powerset。没有一个内置的itertools函数可以做到这一点(据我所知)

编辑可能在标题中使用“set”有误导性。这里的秩序很重要。”ca'!='ac'

我想要的示例:

print( powerset_with_replacement(['abc']) )
# yeilds
('a',)
('b',)
('c',)
('a', 'a')
('a', 'b')
('a', 'c')
('b', 'b')
('b', 'c')
('c', 'c')
('a', 'a', 'a')
('a', 'a', 'b')
('a', 'a', 'c')
('a', 'b', 'b')
('a', 'b', 'c')
('a', 'c', 'c')
('b', 'b', 'b')
('b', 'b', 'c')
('b', 'c', 'c')
('c', 'c', 'c')
我已经走了这么远了,但看起来很乱。。我想知道是否有一种更干净或更像蟒蛇的方法来做到这一点。非常感谢您的帮助

有没有办法去掉展平函数,或者把它放在主函数中

from itertools import combinations_with_replacement
import collections

def flatten(it):
    for x in it:
        if (isinstance(x, collections.abc.Iterable) and
            not isinstance(x, tuple)):
            yield from flatten(x)
        else:
            yield x

def powerset_with_replacement(list1):
   for i in range(1,len(list1)+1):
      yield( combinations_with_replacement(list1, i) )

y = flatten(powerset_with_replacement(list('abc')))

for x in y:
    print(x)

这可能是一种更优雅的方式:我不认为有任何替代品。注意“aa”和“aaa”在我的输出中是怎样的。