我有一个文件:test.txt
,每行有一个句子。
Hello World
99 Bottles of Beer
Humpty Dumpty Sat on the wall
我希望生成一个输出,显示来自该文件的输入的所有组合(即 2n-1 组合)。在上面的例子中,算法将溢出以下内容 - 每个组合都用竖线分隔 (|
)
Hello World
99 Bottles of Beer
Humpty Dumpty Sat on the wall
Hello World | 99 Bottles of Beer
Hello World | Humpty Dumpty Sat on the wall
99 Bottles of Beer | Humpty Dumpty Sat on the wall
Hello World | 99 Bottles of Beer | Humpty Dumpty Sat on the wall
理想情况下,我希望在 bash 或 python 或 perl 脚本中完成此操作,但我愿意接受建议。
最佳答案
import itertools
l = [s.strip() for s in open('test.txt')]
for i in range(len(l)):
print '\n'.join(map(' | '.join, itertools.combinations(l, i + 1)))
产生
Hello World
99 Bottles of Beer
Humpty Dumpty Sat on the wall
Hello World | 99 Bottles of Beer
Hello World | Humpty Dumpty Sat on the wall
99 Bottles of Beer | Humpty Dumpty Sat on the wall
Hello World | 99 Bottles of Beer | Humpty Dumpty Sat on the wall
如果您不喜欢 '\n'.join()
的风格(我不确定我喜欢),您可以将其替换为显式循环:
for i in range(len(l)):
for c in map(' | '.join, itertools.combinations(l, i + 1)):
print c
这有点冗长,但更经济。
关于python - 对句子上的所有 k 执行 K 组合的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13739452/