gpt4 book ai didi

python - Itertools 函数生成唯一的排列

转载 作者:行者123 更新时间:2023-11-28 21:04:32 24 4
gpt4 key购买 nike

我想知道是否有 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 或类似的函数来实现此目的?

最佳答案

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 时,这将以不太理想的方式运行:

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')}

关于python - Itertools 函数生成唯一的排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45114791/

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