迭代列表的每个可能的 n 采样

Iterate over every possible n-sampling of a list

如果我对 itertools "combinatoric iterators" doc 的理解正确,其思想是为每个常见的组合迭代提供一组标准函数。

但我今天错过了一个。我需要迭代每个 ordered 项的重复项组合。

combination_with_replacement('abcd', 4) 产量

('a', 'a', 'a', 'a')
('a', 'a', 'a', 'b')
('a', 'a', 'a', 'c')
('a', 'a', 'a', 'd')
('a', 'a', 'b', 'b')
('a', 'a', 'b', 'c')
('a', 'a', 'b', 'd')
('a', 'a', 'c', 'c')
('a', 'a', 'c', 'd')
... etc

但是(即使结果是排序的元组),这些组合不是 有序的

我希望从理想中获得更多结果 ordered_combination_with_replacement('abcd', 4) 因为我需要区分

('a', 'a', 'a', 'a')
('a', 'a', 'a', 'b')
('a', 'a', 'b', 'a')
('a', 'b', 'a', 'a')
('b', 'a', 'a', 'a')
('a', 'a', 'a', 'c')
('a', 'a', 'c', 'a')
... etc

换句话说:今天的订单很重要。

itertool是否提供这样的迭代?为什么没有,或者为什么我错过了?
迭代这些的标准方法是什么?
我需要自己编写这个通用迭代器吗?

总结一些评论,有(至少)两种方法:

itertools.combinations_with_replacement("abcd", 4)

itertools.product("abcd", repeat=4)

两者都产生所需的结果:

[('a', 'a', 'a', 'a'),
 ('a', 'a', 'a', 'b'),
 ('a', 'a', 'a', 'c'),
 ('a', 'a', 'a', 'd'),
 ('a', 'a', 'b', 'a'),
 ...