Python X 项和长度 X+1 的所有可能组合/排列

问题描述

我到处搜索,但找不到适合我的问题的内容。 假设我有三个数字:['1','2','3']。

无论是否使用 itertool,我都想要长度为 4 的所有可能组合/排列,并且我只想要包含这 3 个数字的组合(我不想要“1111”或“1221”等)。

想要的结果是这样的:
1 2 3 1
1 1 2 3
2 2 3 1

解决方法

from itertools import combinations_with_replacement as irep
res = [' '.join(x) for x in irep('123',4) if {'1','2','3'}.issubset(x)]

# output
# ['1123','1223','1233']

from itertools import product
res= [' '.join(x) for x in product('123',repeat=4) if {'1','3'}.issubset(x)]
# output
# ['1123','1132','1213','1231','1232','1233',# '1312','1321','1322','1323','1332','2113','2123',# '2131','2132','2133','2213','2231','2311','2312',# '2313','2321','2331','3112','3121','3122','3123',# '3132','3211','3212','3213','3221','3231','3312','3321']
,
import itertools

elements = ['1','3']
permutations = [''.join(combination) for combination in 
                itertools.product(elements,repeat = 4) if 
                all(elem in combination for elem in elements)]

这是否会产生您正在寻找的内容?

代码产生以下输出:

['1123','1312','2131','2313','3132','3321']

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...