获取单词列表的组合

时间:2014-08-01 09:46:22

标签: python bash

我正在尝试编写一个小脚本(bash或python),它会提供以下格式输出的单词列表组合。

List 1 | List 2 | List 3
Like   | Big    | Trucks
Hate   | Medium | Cars
       | Small  |

并返回类似于以下内容的结果

Like
Hate
Like Big
Like Medium
Like Small
Like Big Trucks
Like Big Cars
Like Medium Trucks
Like Medium Cars
Like Small Trucks
Like Small Cars
Hate Big
Hate Medium
Hate Small
Hate Big Trucks
Hate Big Cars
Hate Medium Trucks
Hate Medium Cars
Hate Small Trucks
Hate Small Cars
Big Trucks
Big Cars
Medium Trucks
Medium Cars
Small Trucks
Small Cars
Trucks
Cars

请注意这些单词是如何保持与它们来自的列表相同的顺序。

1 个答案:

答案 0 :(得分:4)

您正在寻找的内容可以使用itertools模块在​​python中轻松完成。

import itertools

list1 = ['Like', 'Hate']
list2 = ['Big', 'Medium', 'Small']
list3 = ['Trucks', 'Cars']

sub23 =  [' '.join(x) for x in itertools.product(list2, list3)]
sub12 = [' '.join(x) for x in itertools.product(list1, list2 + sub23)]
res = list1 + sub12 + sub23 + list3
print res

输出:

['Like',
 'Hate',
 'Like Big',
 'Like Medium',
 'Like Small',
 'Like Big Trucks',
 'Like Big Cars',
 'Like Medium Trucks',
 'Like Medium Cars',
 'Like Small Trucks',
 'Like Small Cars',
 'Hate Big',
 'Hate Medium',
 'Hate Small',
 'Hate Big Trucks',
 'Hate Big Cars',
 'Hate Medium Trucks',
 'Hate Medium Cars',
 'Hate Small Trucks',
 'Hate Small Cars',
 'Big Trucks',
 'Big Cars',
 'Medium Trucks',
 'Medium Cars',
 'Small Trucks',
 'Small Cars',
 'Trucks',
 'Cars']

Ps:这个发行背后的逻辑是"奇怪"至少可以说。也许你可以通过提供背后的真实逻辑得到更好的答案:)