python - 对句子上的所有 k 执行 K 组合的算法

标签 python bash combinations

我有一个文件: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/

相关文章:

bash - 是否可以使用 awk 打印文件中的所有行,然后对单个列执行命令?

python - 在Python中生成成功集的所有组合

Python所有数据组合

python - Keras 中的逐像素加权损失函数 - TensorFlow 2.0

python - 如何在同一目录中的另一个 python 脚本中调用 python 脚本?

bash - 如何在不实际更改到该目录的情况下从特定目录执行命令

java - 检索特定组合

python - 浮点计算调试

python - requests.get(url) 从 kubernetes api 返回错误代码 404,而响应可以通过curl/GET 获取

bash - macOS Catalina 10.15(beta) - 为什么 ~/.bash_profile 不是由我的 shell 提供的?