【问题标题】:Create every possible string combination by the abc通过 abc 创建每个可能的字符串组合
【发布时间】:2020-03-19 01:04:41
【问题描述】:

我正在尝试创建一个可以为一个单词生成所有可能的组合的东西,直到 4 个字符。

例如将以 a,b,c...aa,ab,ac...aaa,aab,aac...aaaa,aaab,aaac....zzzx,zzzy,zzzz 开头

我最接近的东西是:

import itertools
for i in range(4):
    for combination in itertools.combinations('abcdefghijklmnopqrstuvwxyz-([{0123456789', i):
        word = str(combination).replace("'", '').replace("(", '').replace(")", '').replace(" ", '').replace(",", '')
        print(word)

问题在于,它不会创建具有相同字符的组合,例如 aa、bb、cc。

【问题讨论】:

  • 完全相同的代码 - 将 combinations 替换为 combinations_with_replacement: docs.python.org/2/library/…
  • 刚刚注意到。它并不能提供一切。如您所见,例如没有 (b,a,a)。
  • 你应该使用itertools.product 然后 - combinations 暗示不相关的顺序。

标签: python-3.x


【解决方案1】:

因为顺序很有意义-itertools.product 是要走的路:

import itertools
for i in range(4):
    for combination in itertools.product('abcdefghijklmnopqrstuvwxyz-([{0123456789', repeat=i):
        word = ''.join(combination)
        print(word)

【讨论】:

  • 其实顺序并不重要,这正是我所需要的!谢谢!
  • 很高兴它起作用了 :) 我还调整了创建 word 的部分(你拥有多个 replace 的那个)
【解决方案2】:

只需使用combinations_with_replacement 而不是combinations

from itertools import combinations_with_replacement

list(combinations_with_replacement('abc', 3))
[('a', 'a', 'a'),
 ('a', 'a', 'b'),
 ('a', 'a', 'c'),
 ('a', 'b', 'b'),
 ('a', 'b', 'c'),
 ('a', 'c', 'c'),
 ('b', 'b', 'b'),
 ('b', 'b', 'c'),
 ('b', 'c', 'c'),
 ('c', 'c', 'c')]

【讨论】:

  • 刚刚注意到。它并不能提供一切。如您所见,例如没有 (b,a,a)。
猜你喜欢
  • 2013-12-21
  • 1970-01-01
  • 2013-06-02
  • 1970-01-01
  • 2015-03-10
  • 2021-11-14
  • 2011-06-25
  • 2016-10-16
  • 1970-01-01
相关资源
最近更新 更多