【问题标题】:Python 3.4.3 - How to make textwrap work with itertoolsPython 3.4.3 - 如何使 textwrap 与 itertools 一起工作
【发布时间】:2015-08-18 19:44:06
【问题描述】:

我正在使用此代码:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import textwrap
import itertools

a = []

a.append('word1')
a.append('word2')
a.append('word3')
a.append('word4')
a.append('word5')
a.append('word6')
a.append('word7')
a.append('word8')
a.append('word9')
a.append('word10')

for permutation in itertools.permutations(a,):
    permutation = textwrap.TextWrapper(len=60,break_long_words=False,replace_whitespace=False)
    print(' '.join(permutation))    

并从herehere获取一些信息,但无法解决我的问题。

我只想将这些单词排列成所有可能的组合,不可重复的短语,长度为 60 个字符。

【问题讨论】:

  • 我不确定你想在那里使用文本包装器做什么。此外,您正在覆盖 for 循环中的排列。
  • 我正在尝试仅打印长度为 60 char len 的短语。

标签: python python-3.4 itertools


【解决方案1】:

这将打印所有排列组合成单个字符串时长度为 60:

for permutation in itertools.permutations(a):
    s = ' '.join(permutation)
    if len(s) == 60:
        print(s)

但无论如何这样做并没有多大意义,因为序列的排列将始终包含该序列的所有元素,因此组合字符串将始终具有相同的长度,并且只有单词的顺序发生变化.

所以您也可以先进行检查,然后再循环排列。

或者您可以生成允许不同长度的组合。

【讨论】:

  • 无法正常工作。它只是让我进入一个永远循环并且不打印 60 char len =/
  • 不,这不可能是一个无限循环。但是您很可能找不到任何结果,尤其是对于您问题中的那些示例字符串(没有组合会给您长度为 60 的字符串)。
  • 我正在尝试这个但不工作。 '#!/usr/bin/env python3 # -- coding: utf-8 -- import textwrap import itertools a = '只是测试这个来尝试让它工作'.split() 进行排列在 itertools.permutations(a,): s = ' '.join(permutation) if len(s) == 60: print(s)'
  • 实际上,您的脚本运行良好,所有排列的长度均为 60 个字符(9 个空格,5 个字母/单词 * 9 个单词,6 个字母/单词 * 1 个单词)。但是,python 需要一段时间才能打印出所有 3628800 个排列。
  • 它不像我想要的那样工作。 #!/usr/bin/env python3 # -*- coding: utf-8 -*- import textwrap import itertools a=[] a.append('test') a.append('testttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt') a.append('testing') a.append('tested') a.append('tester') for permutation in itertools.permutations(a,): s = ' '.join(permutation) if len(s) == 60: print(s) 这个公式不打印任何东西。
猜你喜欢
  • 1970-01-01
  • 2011-10-13
  • 2019-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-20
  • 1970-01-01
  • 2012-08-04
相关资源
最近更新 更多