我想知道是否有itertools
方法可以产生以下组合/排列:
list = ['x', 'o']
# when character 'x' is allowed to occupy 1 place with total places of 4:
a = [['o','o','o','x'],
['o','o','x','o'],
['o','x','o','o'],
['x','o','o','o']]
# when character 'x' is allowed to occupy 2 places with total places of 4:
b = [['o','o','x','x'],
['o','x','x','o'],
['x','x','o','o'],
['x','o','x','o'],
['o','x','o','x'],
['x','o','o','x']]
我想知道是否有办法使用itertools.product
或类似功能来实现这一目标?
答案 0 :(得分:3)
itertools.permutations
也接受字符串作为参数:
from itertools import permutations
>>> list(permutations("ooox"))
[('o', 'o', 'o', 'x'), ('o', 'o', 'x', 'o'), ('o', 'o', 'o', 'x'), ('o', 'o', 'x', 'o'), ('o', 'x', 'o', 'o'), ('o', 'x', 'o', 'o'), ('o', 'o', 'o', 'x'), ('o', 'o', 'x', 'o'), ('o', 'o', 'o', 'x'), ('o', 'o', 'x', 'o'), ('o', 'x', 'o', 'o'), ('o', 'x', 'o', 'o'), ('o', 'o', 'o', 'x'), ('o', 'o', 'x', 'o'), ('o', 'o', 'o', 'x'), ('o', 'o', 'x', 'o'), ('o', 'x', 'o', 'o'), ('o', 'x', 'o', 'o'), ('x', 'o', 'o', 'o'), ('x', 'o', 'o', 'o'), ('x', 'o', 'o', 'o'), ('x', 'o', 'o', 'o'), ('x', 'o', 'o', 'o'), ('x', 'o', 'o', 'o')]
和
>>> list(permutations("ooxx"))
[('o', 'o', 'x', 'x'), ('o', 'o', 'x', 'x'), ('o', 'x', 'o', 'x'), ('o', 'x', 'x', 'o'), ('o', 'x', 'o', 'x'), ('o', 'x', 'x', 'o'), ('o', 'o', 'x', 'x'), ('o', 'o', 'x', 'x'), ('o', 'x', 'o', 'x'), ('o', 'x', 'x', 'o'), ('o', 'x', 'o', 'x'), ('o', 'x', 'x', 'o'), ('x', 'o', 'o', 'x'), ('x', 'o', 'x', 'o'), ('x', 'o', 'o', 'x'), ('x', 'o', 'x', 'o'), ('x', 'x', 'o', 'o'), ('x', 'x', 'o', 'o'), ('x', 'o', 'o', 'x'), ('x', 'o', 'x', 'o'), ('x', 'o', 'o', 'x'), ('x', 'o', 'x', 'o'), ('x', 'x', 'o', 'o'), ('x', 'x', 'o', 'o')]
要将它们存储在您的问题中所示的列表列表中,您可以使用map(list, permutations("ooox"))
。
正如您在评论部分中提到的,我们可以为该作业编写一个特定的函数,它接受您想要的输入,但请注意,当第一个字符串长度不是1时,这将以不太理想的方式运行: / p>
from itertools import permutations
def iterate(lst, length, places):
return set(permutations(lst[0]*(length-places)+lst[1]*places))
演示:
>>> from pprint import pprint
>>> pprint(iterate(["o","x"], 4, 1))
{('o', 'o', 'o', 'x'),
('o', 'o', 'x', 'o'),
('o', 'x', 'o', 'o'),
('x', 'o', 'o', 'o')}
>>> pprint(iterate(["o","x"], 4, 2))
{('o', 'o', 'x', 'x'),
('o', 'x', 'o', 'x'),
('o', 'x', 'x', 'o'),
('x', 'o', 'o', 'x'),
('x', 'o', 'x', 'o'),
('x', 'x', 'o', 'o')}
答案 1 :(得分:2)
您可以根据itertools.combinations
创建自己的函数(或生成器):
from itertools import combinations
def equivalence_permutations(x, o):
"""Create all unique permutations with `x` x'es and `o` o's."""
total = x+o
for indices in combinations(range(total), x):
lst = ['o']*total
for index in indices:
lst[index] = 'x'
yield lst
combinations
确保索引是唯一的,无需使用set
或任何其他贪婪操作。所以在这种情况下它应该快得多。例如:
>>> list(equivalence_permutations(2, 2)) # 2 x and 2 o
[['x', 'x', 'o', 'o'],
['x', 'o', 'x', 'o'],
['x', 'o', 'o', 'x'],
['o', 'x', 'x', 'o'],
['o', 'x', 'o', 'x'],
['o', 'o', 'x', 'x']]
>>> list(equivalence_permutations(1, 3)) # 1 x and 3 o
[['x', 'o', 'o', 'o'],
['o', 'x', 'o', 'o'],
['o', 'o', 'x', 'o'],
['o', 'o', 'o', 'x']]