在3个字符串列表中生成所有可能的元素组合?

时间:2017-10-29 20:31:58

标签: python string combinations permutation

我需要在每个字符串列表中生成所有可能的EACH元素组合

list1 = ['The girl', 'The boy']
list2 = ['wears', 'touches', 'tries']
list3 = ['a red sweater', 'a blue sweater', 'a yellow sweater', 'a white sweater']

因此,结果是一个字符串列表,将每个元素组合在一起,相互结合:

The girl wears a red sweater
The boy wears a red sweater
The girl touches a red sweater
The boy touches a red sweater
The girl wears a blue sweater
The boy wears a yellow sweater
(ETC...)

只要获得所有组合,我就不特别关心输出的顺序。

根据我的研究,我猜“排列”将是一个解决方案,但我只找到了关于数字列表的排列或字符串中每个字母的组合的几个答案。这些都不是我需要的。 我需要组合列表中的文本块。

如何创建一长串的句子,其中包含每个字符串列表中不同元素的所有组合?

谢谢

3 个答案:

答案 0 :(得分:2)

只需要一堆简单的for循环即可。诀窍是打印z,y,x的顺序。

list1 = ['The girl', 'The boy']
list2 = ['wears', 'touches', 'tries']
list3 = ['a red sweater', 'a blue sweater', 'a yellow sweater', 'a white sweater']

for x in list3:
    for y in list2:
        for z in list1:
            print (z,y,x)

输出;

The girl wears a red sweater
The boy wears a red sweater
The girl touches a red sweater
The boy touches a red sweater
The girl tries a red sweater
The boy tries a red sweater
The girl wears a blue sweater
The boy wears a blue sweater
The girl touches a blue sweater
The boy touches a blue sweater
The girl tries a blue sweater
The boy tries a blue sweater
The girl wears a yellow sweater
The boy wears a yellow sweater
The girl touches a yellow sweater
The boy touches a yellow sweater
The girl tries a yellow sweater
The boy tries a yellow sweater
The girl wears a white sweater
The boy wears a white sweater
The girl touches a white sweater
The boy touches a white sweater
The girl tries a white sweater
The boy tries a white sweater

答案 1 :(得分:1)

使用itertools.product,这是笛卡尔积的便捷工具。然后join产品:

from itertools import product
lst = [' '.join(p) for p in product(list1, list2, list3)]

from pprint import pprint
pprint(lst)
['The girl wears a red sweater',
 'The girl wears a blue sweater',
 'The girl wears a yellow sweater',
 'The girl wears a white sweater',
 'The girl touches a red sweater',
 'The girl touches a blue sweater',
 'The girl touches a yellow sweater',
 'The girl touches a white sweater',
 'The girl tries a red sweater',
 'The girl tries a blue sweater',
 'The girl tries a yellow sweater',
 'The girl tries a white sweater',
 'The boy wears a red sweater',
 'The boy wears a blue sweater',
 'The boy wears a yellow sweater',
 'The boy wears a white sweater',
 'The boy touches a red sweater',
 'The boy touches a blue sweater',
 'The boy touches a yellow sweater',
 'The boy touches a white sweater',
 'The boy tries a red sweater',
 'The boy tries a blue sweater',
 'The boy tries a yellow sweater',
 'The boy tries a white sweater']

答案 2 :(得分:0)

使用itertools的产品,其简单如下:

import itertools
["{x} {y} {z}".format(x=x,y=y,z=z) for x,y,z in itertools.product(list1, list2, list3)]

在python 3.6中,您可以放弃format调用

[f"{x} {y} {z}" for x,y,z in itertools.product(list1, list2, list3)]