【问题标题】:Writing all possible combinations of a characters in a string to a file using Python使用 Python 将字符串中字符的所有可能组合写入文件
【发布时间】:2018-02-08 23:05:45
【问题描述】:

我有一个字符串 s="abcde"。我想生成所有可能的排列并将它们写入 txt 文件。 输出文件.txt

一个 b C d 啊 抗体 交流 广告 ae 巴 bb 公元前 BD 是 约 CB 抄送 光盘 ce 大 D b 直流 dd 德 一个 eb 欧共体 编 ee ... ... 伊达 eedb eedc eedd eeede EEEA eeeb EEEC eeed 哎呀

我使用了 itertools,但它总是以 aaaaa 开头。

【问题讨论】:

  • 请分享您的代码。看起来您只需要生成长度为 1、2、3 等的“排列”……直到您想要的长度,这可以通过 for 循环轻松完成。
  • 这不是排列!向我们展示您的代码和预期输出与实际输出

标签: python file combinations cartesian-product


【解决方案1】:
import itertools

s="abcde"

def upto_n(s,n):

    out = []

    for i in range(1,n+1,1):

        out += list(itertools.combinations(s, i))

    return out

print upto_n(s,2)
print upto_n(s,3)

输出

 [('a',), ('b',), ('c',), ('d',), ('e',), ('a', 'b'), ('a', 'c'), ('a', 'd'), ('a', 'e'), ('b', 'c'), ('b', 'd'), ('b', 'e'), ('c', 'd'), ('c', 'e'), ('d', 'e')]

 [('a',), ('b',), ('c',), ('d',), ('e',), ('a', 'b'), ('a', 'c'), ('a', 'd'), ('a', 'e'), ('b', 'c'), ('b', 'd'), ('b', 'e'), ('c', 'd'), ('c', 'e'), ('d', 'e'), ('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'b', 'e'), ('a', 'c', 'd'), ('a', 'c', 'e'), ('a', 'd', 'e'), ('b', 'c', 'd'), ('b', 'c', 'e'), ('b', 'd', 'e'), ('c', 'd', 'e')]

【讨论】:

  • 根据 OP 的输出,这也是不正确的。他们也想要重复的字符。
【解决方案2】:

itertools.permutations 有 2 个参数,即排列的可迭代和长度。如果不指定第二个参数,则默认为 len(iterable)。要获得所有长度,您需要打印每个长度的排列:

import itertools
s = "abcde"
for i in range(len(s)):
    for permutation in (itertools.permutations(s, i+1)):
        print ("".join(permutation))

来源:https://docs.python.org/2/library/itertools.html#itertools.permutations

【讨论】:

  • 是的,排列确实需要两个元素。我写的很匆忙,忘记了:)
猜你喜欢
  • 2015-05-06
  • 2017-11-11
  • 2015-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多