Python 对所有K个句子执行K组合的算法

Python 对所有K个句子执行K组合的算法,python,bash,combinations,Python,Bash,Combinations,我有一个文件:test.txt,每行有一个句子 你好,世界 99瓶啤酒 汉普蒂·达姆蒂坐在墙上 我希望生成一个输出,显示该文件输入的所有组合(即2n-1组合)。在上面的实例中,算法将溢出以下内容-每个组合都要用管道分隔(|) 你好,世界 99瓶啤酒 汉普蒂·达姆蒂坐在墙上 你好,世界| 99瓶啤酒 你好,世界|汉普蒂·达姆蒂坐在墙上 99瓶啤酒| Humpty Dumpty坐在墙上 你好,世界| 99瓶啤酒|汉普蒂·达姆蒂坐在墙上 理想情况下,我希望用bash、python或perl脚本完成

我有一个文件:
test.txt
,每行有一个句子

你好,世界
99瓶啤酒
汉普蒂·达姆蒂坐在墙上
我希望生成一个输出,显示该文件输入的所有组合(即2n-1组合)。在上面的实例中,算法将溢出以下内容-每个组合都要用管道分隔(
|

你好,世界
99瓶啤酒
汉普蒂·达姆蒂坐在墙上
你好,世界| 99瓶啤酒
你好,世界|汉普蒂·达姆蒂坐在墙上
99瓶啤酒| Humpty Dumpty坐在墙上
你好,世界| 99瓶啤酒|汉普蒂·达姆蒂坐在墙上
理想情况下,我希望用bash、python或perl脚本完成这项工作,但我愿意接受建议

你能行

import itertools

file = open("test.txt")
lines = files.readlines()

current = []
for i in range(len(lines):
    current.append(i)

    for combination in set(itertools.permutations(current)):
        for l in combination:
            output+=' | '.join(lines[l])
        output+= '\n'
print output
我对我的itertools&set技能感到厌倦,但这应该是可行的,除非有内存限制

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

这稍微有点冗长,但更经济。

您尝试过并失败了吗?如果是,那是什么?不是(2^n)-1吗?没有字符串的输出不是有效的吗?哦,等等,我忘了我可以使用组合。刘海头贴在墙上。谢谢你们!我花了最后1个小时尝试使用for循环来完成这项工作,但仍然无法生成我想要的输出。屈服于python的itertools的威力