【问题标题】:Python all possible combinations/permutation of X items and of length X+1Python X 项和长度 X+1 的所有可能组合/排列
【发布时间】:2021-02-18 08:10:57
【问题描述】:

我一直在到处寻找,但找不到适合我的问题的东西。 假设我有三个数字:['1','2','3']。

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

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

【问题讨论】:

  • 2 3 2 1 怎么样?
  • 问题不清楚。一方面它说“我不想要'1111'或'1221'等等”,但另一方面应该允许'1123'或'2231'。你的标准是什么?另外,如果集合只包含 ['1','2','3'] 但结果中应该有 4 个值,我们如何避免重复?
  • 我无法很好地解释我想要什么,但@Aven Desta 给了我我真正想要的东西,感谢发帖 :)

标签: python-3.x combinations permutation itertools


【解决方案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','2','3'}.issubset(x)]
# output
# ['1123', '1132', '1213', '1223', '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']

【讨论】:

  • 第二个正是我正在寻找的!非常感谢!
【解决方案2】:
import itertools

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

这会产生您想要的东西吗?

代码产生以下输出:

['1123', '1132', '1213', '1223', '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']

【讨论】:

  • 是的!这个也可以,谢谢分享!
猜你喜欢
  • 1970-01-01
  • 2014-12-20
  • 1970-01-01
  • 1970-01-01
  • 2013-01-17
  • 1970-01-01
  • 2019-03-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多