python阵列的所有排列

发布于 2025-02-01 16:10:49 字数 878 浏览 2 评论 0原文

我有一个数组。我想生成来自该数组的所有排列,包括单个元素,重复元素,更改订单等

arr = ['A', 'B', 'C']

from itertools import permutations
perms = [''.join(p) for p in permutations(['A','B','C'])]
print(perms)

或使用这样的循环:

def permutations(head, tail=''):
if len(head) == 0:
    print(tail)
else:
    for i in range(len(head)):
        permutations(head[:i] + head[i+1:], tail + head[i])
        
arr= ['A', 'B', 'C']
permutations(arr)

我只能得到:

['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA']

但是我想要的是:

['A', 'B', 'C', 
 'AA', 'AB', 'AC', 'BB', 'BA', 'BC', 'CA', 'CB', 'CC', 
 'AAA', 'AAB', 'AAC', 'ABA', 'ABB', 'ACA', 'ACC', 'BBB', 'BAA', 'BAB', 'BAC', 'CCC', 'CAA', 'CCA'.]

结果是给出的数组中的所有排列。由于数组是3个元素,并且所有元素都可以重复,因此它会生成3^3(27)方式。我知道必须有一种方法可以做到这一点,但是我不能完全正确地理解逻辑。

I have an array. I want to generate all permutations from that array, including single element, repeated element, change the order, etc. For example, say I have this array:

arr = ['A', 'B', 'C']

And if I use the itertools module by doing this:

from itertools import permutations
perms = [''.join(p) for p in permutations(['A','B','C'])]
print(perms)

Or using loop like this:

def permutations(head, tail=''):
if len(head) == 0:
    print(tail)
else:
    for i in range(len(head)):
        permutations(head[:i] + head[i+1:], tail + head[i])
        
arr= ['A', 'B', 'C']
permutations(arr)

I only get:

['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA']

But what I want is:

['A', 'B', 'C', 
 'AA', 'AB', 'AC', 'BB', 'BA', 'BC', 'CA', 'CB', 'CC', 
 'AAA', 'AAB', 'AAC', 'ABA', 'ABB', 'ACA', 'ACC', 'BBB', 'BAA', 'BAB', 'BAC', 'CCC', 'CAA', 'CCA'.]

The result is all permutations from the array given. Since the array is 3 element and all the element can be repetitive, so it generates 3^3 (27) ways. I know there must be a way to do this but I can't quite get the logic right.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

海螺姑娘 2025-02-08 16:10:49

一个生成所有序列的发电机(如果您尝试用尽它,它具有无限的长度):

from itertools import product


def sequence(xs):
    n = 1
    while True:
        yield from (product(xs, repeat=n))
        n += 1


# example use: print first 100 elements from the sequence
s = sequence('ABC')
for _ in range(100):
    print(next(s))

输出:

('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')
...

当然,如果您不想要元组,但是字符串,只需替换next(s)带有'''。加入(NEXT(s)),即:

    print(''.join(next(s)))

如果您不希望序列超过原始集合的长度:

from itertools import product


def sequence(xs):
    n = 1
    while n <= len(xs):
        yield from (product(xs, repeat=n))
        n += 1


for element in sequence('ABC'):
    print(''.join(element))

当然,在有限的情况下,这也是如此:

from itertools import product

xs = 'ABC'
for s in (''.join(x) for n in range(len(xs)) for x in product(xs, repeat=n+1)):
    print(s)

编辑:在评论中,OP要求对(产品(xs,repot = n)) part的产量说明。

product()itertools生成迭代的笛卡尔产品的函数,这是一种奇特的方式,可以说您从第一个itobles中获得了所有可能的元素组合,有了第二

list(product([1, 2], [3, 4])) == [(1, 3), (1, 4), (2, 3), (2, 4)]

list(product('AB', 'AB')) == [('A', 'A'), ('A', 'B'), ('B', 'A'), ('B', 'B')]

元素 > product()带有list()在此处,这是因为product()返回生成器并将生成器传递到list()< /代码>将生成器耗尽到列表中,以进行打印。

product()的最后一步是,您还可以给它一个可选的重复参数,该参数告诉product()做同一件事,但只需重复一定次数即可。例如:

list(product('AB', repeat=2)) == [('A', 'A'), ('A', 'B'), ('B', 'A'), ('B', 'B')]

因此,您可以查看如何调用product(xs,repot = n)将生成您追求的所有序列,如果您从n = 1和继续用尽它,n

最后,的收益率是一种在您自己的发电机中一次从另一个发电机的产生产生的方法。例如,来自某些_gen收益率与:

for x in some_gen:
    yield x

so,从(product(xs,repot = n))的收益率相同:

for p in (product(xs, repeat=n)):
    yield p

A generator that would generate all sequences as you describe (which has infinite length if you would try to exhaust it):

from itertools import product


def sequence(xs):
    n = 1
    while True:
        yield from (product(xs, repeat=n))
        n += 1


# example use: print first 100 elements from the sequence
s = sequence('ABC')
for _ in range(100):
    print(next(s))

Output:

('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')
...

Of course, if you don't want tuples, but strings, just replace the next(s) with ''.join(next(s)), i.e.:

    print(''.join(next(s)))

If you don't want the sequences to exceed the length of the original collection:

from itertools import product


def sequence(xs):
    n = 1
    while n <= len(xs):
        yield from (product(xs, repeat=n))
        n += 1


for element in sequence('ABC'):
    print(''.join(element))

Of course, in that limited case, this will do as well:

from itertools import product

xs = 'ABC'
for s in (''.join(x) for n in range(len(xs)) for x in product(xs, repeat=n+1)):
    print(s)

Edit: In the comments, OP asked for an explanation of the yield from (product(xs, repeat=n)) part.

product() is a function in itertools that generates the cartesian product of iterables, which is a fancy way to say that you get all possible combinations of elements from the first iterable, with elements from the second etc.

Play around with it a bit to get a better feel for it, but for example:

list(product([1, 2], [3, 4])) == [(1, 3), (1, 4), (2, 3), (2, 4)]

If you take the product of an iterable with itself, the same happens, for example:

list(product('AB', 'AB')) == [('A', 'A'), ('A', 'B'), ('B', 'A'), ('B', 'B')]

Note that I keep calling product() with list() around it here, that's because product() returns a generator and passing the generator to list() exhausts the generator into a list, for printing.

The final step with product() is that you can also give it an optional repeat argument, which tells product() to do the same thing, but just repeat the iterable a certain number of times. For example:

list(product('AB', repeat=2)) == [('A', 'A'), ('A', 'B'), ('B', 'A'), ('B', 'B')]

So, you can see how calling product(xs, repeat=n) will generate all the sequences you're after, if you start at n=1 and keep exhausting it for ever greater n.

Finally, yield from is a way to yield results from another generator one at a time in your own generator. For example, yield from some_gen is the same as:

for x in some_gen:
    yield x

So, yield from (product(xs, repeat=n)) is the same as:

for p in (product(xs, repeat=n)):
    yield p
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文