【问题标题】:Python itertools permutations how to include repeating characters [duplicate]Python itertools排列如何包含重复字符[重复]
【发布时间】:2012-12-22 21:51:49
【问题描述】:

可能重复:
Power set and Cartesian Product of a set python

使用 Python Itertools.permutations() 我想接收和输出带有重复字符的排列。例如,下面是我的函数及其当前输出。

def perm(n,i):
    b = 0
    while b < n:
        n= n -1
        from itertools import permutations as p
        file.write('\n'.join([''.join(item) for item in p(i,n)]))
perm(4,'0123')

输出是:

012
013
021
023
031
032
102
103
120
123
130
132
201
203
210
213
230
231
301
302
310
312
320
321.....

我如何获得像 112 或 222 这样的输出?

据我了解,组合不是特定于排列的顺序。我正在寻找的是找到所有组合,然后是每个组合的每个排列。这可能吗?

【问题讨论】:

  • 为什么每次循环都导入permutations?为什么; 延长线?你至少可以把它清理干净..

标签: python permutation itertools


【解决方案1】:

您根本不想要排列。你想要笛卡尔积:

import itertools

def perm(n, seq):
    for p in itertools.product(seq, repeat=n):
        file.write("".join(p))
        file.write("\n")

perm(4, "0123")

【讨论】:

    【解决方案2】:

    您似乎正在寻找的是Cartesian product,而不是排列,它也由 itertools 提供。

    您最好熟悉排列、组合、替换组合和笛卡尔积之间的区别,以确定最适合您的应用程序的方法,但很有可能,您正在寻找其他选项。

    【讨论】:

    • 我也想了一会儿,但 OP 似乎同时想要 012102 - 或者至少他没有在他的列表中评论它 - 在这种情况下他可能在itertools.product之后。
    猜你喜欢
    • 1970-01-01
    • 2017-03-10
    • 2018-11-12
    • 2019-03-15
    • 2020-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多