【发布时间】:2014-12-03 03:31:30
【问题描述】:
我正在做一些分词实验,如下所示。
lst 是一个字符序列,output 是所有可能的单词。
lst = ['a', 'b', 'c', 'd']
def foo(lst):
...
return output
output = [['a', 'b', 'c', 'd'],
['ab', 'c', 'd'],
['a', 'bc', 'd'],
['a', 'b', 'cd'],
['ab', 'cd'],
['abc', 'd'],
['a', 'bcd'],
['abcd']]
我在itertools 库中检查了combinations 和permutations,
也试过combinatorics.
但是,我似乎看错了一面,因为这不是纯粹的排列组合......
似乎我可以通过使用大量循环来实现这一点,但效率可能会很低。
编辑
词序很重要,因此['ba', 'dc'] 或['cd', 'ab'] 等组合无效。
顺序应该总是从左到右。
编辑
@Stuart 的解决方案在 Python 2.7.6 中不起作用
编辑
@Stuart 的解决方案确实适用于 Python 2.7.6,请参阅下面的 cmets。
【问题讨论】:
标签: python combinations permutation combinatorics